Mysql如何给用户授权?Mysql如何收回用户权限?

使用Create User 命令创建的用户,默认没有对业务数据库的操作权限,对用户权限的操作,主要使用Grant 命令和REVOKE命令,MySql有哪些权限呢?官方提供了 show privileges命令查看。

Mysql主要使用的有以下权限:

  • create/drop 创建新的数据库/表、删除已有的数据库/表
  • select/insert/update/delete 对表的操作
  • index 创建/删除索引
  • alter 更改表的结构、重新命名表
  • create routine 创建程序、函数、程序
  • execute 执行程序
  • grant 允许授权给其它用户
  • file

1.给用户授权

授权语法

grant 权限1,权限2 ... on 数据库.表 to 用户名@用户地址  [identified by '密码']

示例1: 给用户zhangsan 授权select/insert/delete/update 操作数据库test的所有表

 grant select,insert,delete,update on test.* to zhangsan@'%';

实例2: 创建用户lisi, 并授权所有权限

mysql> create user lisi@'%' identified by 'test123';
Query OK, 0 rows affected (0.03 sec)

mysql> grant all privileges on *.* to lisi@'%';  #不包含grant 权限
Query OK, 0 rows affected (0.02 sec)

2. 查看权限

查看当前用户的权限

show grants;

show grants for current_user;

查看某个用户的权限

mysql> show grants for zhangsan@'%';
+--------------------------------------------------------------------+
| Grants for zhangsan@%                                              |
+--------------------------------------------------------------------+
| GRANT USAGE ON *.* TO `zhangsan`@`%`                               |
| GRANT SELECT, INSERT, UPDATE, DELETE ON `test`.* TO `zhangsan`@`%` |
+--------------------------------------------------------------------+
2 rows in set (0.00 sec)

3. 收回权限

撤销授权语法

revoke 权限1,权限2 on 数据库.表 from 用户名@用户地址

示例1:收回zhangsan 对数据库test 的 delete权限

mysql> revoke delete on test.* from zhangsan@'%';
Query OK, 0 rows affected (0.01 sec)

mysql> show grants for zhangsan@'%';
+------------------------------------------------------------+
| Grants for zhangsan@%                                      |
+------------------------------------------------------------+
| GRANT USAGE ON *.* TO `zhangsan`@`%`                       |
| GRANT SELECT, INSERT, UPDATE ON `test`.* TO `zhangsan`@`%` |
+------------------------------------------------------------+
2 rows in set (0.00 sec)

实例2: 收回lisi的所有权限

mysql> revoke all privileges on *.* from lisi@'%';
ERROR 1227 (42000): Access denied; you need (at least one of) the SYSTEM_USER privilege(s) for this operation
mysql>
mysql> grant SYSTEM_USER on *.* to root@'%';
Query OK, 0 rows affected (0.01 sec)

mysql> revoke all privileges on *.* from lisi@'%';
Query OK, 0 rows affected (0.02 sec)

mysql> show grants for lisi@'%';
+----------------------------------+
| Grants for lisi@%                |
+----------------------------------+
| GRANT USAGE ON *.* TO `lisi`@`%` |
+----------------------------------+
1 row in set (0.00 sec)

原创文章,作者:zhuji001,如若转载,请注明出处:https://www.zhuji66.com/mysql-privileges-grant-revoke/

本站分享VPS和云服务器信息均来源于网络,如有侵权请邮箱联系zhuji66com@yeah.net。本站不销售任何产品,如遇问题请联系对应客服。