您的位置:首页 > 数据库 > MySQL

mysql stored routine (存储例程) 中 definer 的作用 和实例

2017-12-19 11:54 295 查看
创建 例程语法参见https://dev.mysql.com/doc/refman/5.7/en/create-procedure.html

创建procedure 的语法如下

CREATE
[DEFINER = { user | CURRENT_USER }]
PROCEDURE sp_name ([proc_parameter[,...]])
[characteristic ...] routine_body


definer 的作用是进行一个权限的控制 只有super 权限或者 指定的 procedure 创建者 才能执行这个procedure

只有super 用户才能使用definer 语法

创建一个简单的实例

我是在root@localhost 下面创建的

mysql> delimiter #

mysql> CREATE DEFINER=`hee`@`localhost` PROCEDURE `simpleproc`(OUT param1 INT)
begin select count(*) INTO param1 from `categories`;
end #
mysql> delimiter ;

#调用的时候直接

mysql> call simpleproc(@a);
mysql> select @a;
+------+
| @a   |
+------+
|    6 |
+------+
1 row in set (0.00 sec)


现在我切换到 hee@localhost

本应该 我执行 simpleproc 就可以的 因为当前用户就是hee@localhost 但是仍然失败 代码如下

#我先创建了 hee@localhost 用户 【在root@localhost 下面 创建】
mysql> create user hee@localhost identified by "abc";

#在给了一部分权限给hee@localhost
grant insert,update,select on `api_db`.`categories` to hee@localhost;

# 为什么我没有直接给ALL PRIVILEGES 给 hee@localhost 是因为 不是所有的情况都可以给all privileges 的 我旨在说明 执行 procedure 的权限

# 切换到 hee@localhost

mysql> call simpleproc(@a);
ERROR 1370 (42000): execute command denied to user 'hee'@'localhost' for routine 'api_db.simpleproc'
mysql> select CURRENT_USER;
+---------------+
| CURRENT_USER  |
+---------------+
| hee@localhost |
+---------------+
1 row in set (0.00 sec)


为啥不能执行simpleproc ?

因为在还需要另外的权限

参考 grant 权限列表

https://dev.mysql.com/doc/refman/8.0/en/privileges-provided.html#priv_execute

摘抄

The EXECUTE privilege is required to execute stored routines (procedures and functions).

要执行 procedure 必须拥有execute 权限 这个可以再 mysql.user 表格中查看

EXECUTE 是加载在一个database 上面的

所以

要授权使用

mysql> grant EXECUTE on `api_db`.* to hee@localhost;
Query OK, 0 rows affected (0.00 sec)

mysql> flush privileges;
Query OK, 0 rows affected (0.00 sec)


但是 还是在另外一个终端 (hee@localhost 登陆的终端) 还是执行 call simpleproc(@a)

失败 只要重新登录mysql一下就可以了

mysql> call simpleproc1(@a) ;
Query OK, 1 row affected (0.00 sec)

mysql> select @a
-> ;
+------+
| @a   |
+------+
|    1 |
+------+
1 row in set (0.00 sec)


扩展阅读

Access Control in MySQL Stored Routines: DEFINER, INVOKER & SQL SECURITY
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息