zoukankan      html  css  js  c++  java
  • mysql stored routine (存储例程) 中 definer 的作用 和实例

    创建 例程语法参见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)
    慢慢沉淀自己
  • 相关阅读:
    CentOS7.4安装和配置Zabbix4.0
    CentOS7.4安装jdk1.8.0_201、Tomcat-8.5.38环境
    基于腾讯云CentOS7.4+MySQL5.7+Python3+uWSGI+Nginx的Django项目部署
    Windows Server 2008 R2环境下Apache2.4+Tomcat8配置
    Django2.1.5使用xadmin打造适合国人的后台管理系统
    Django2.1.3 smtp 邮件 553报警
    GitHub的Windows客户端的使用教程
    Ubuntu18.04的网络配置(静态IP和动态IP)
    CentOS6.X、7.X下Jenkins的安装及使用
    CentOS7下搭建Nginx+PHP7的安装配置
  • 原文地址:https://www.cnblogs.com/martinding/p/8059107.html
Copyright © 2011-2022 走看看