MySQL 赋予用户权限命令的简单格式可概括为:grant 权限 on 数据库对象 to 用户@访问权限主机 identified by 密码
grant 普通数据用户,查询、插入、更新、删除 数据库中所有表数据的权利。
1 2 3 4 5 6 7 8 9 10 11
# 赋予查询权限 grant select on test1.* to user1@'%' identified by 'UserPass123%'; # 赋予插入权限 grant insert on test1.* to user1@'%' identified by 'UserPass123%'; # 赋予更新权限 grant update on test1.* to user1@'%' identified by 'UserPass123%'; # 赋予删除权限 grant delete on test1.* to user1@'%' identified by 'UserPass123%';
# 赋予所有权限 grant select, insert, update, delete on test1.* to user1@'%' identified by 'UserPass123%';
特殊说明:最后一天权限百分号%代表远程访问权限。
如何指定访问数据库主机权限
1 2 3 4 5 6 7 8 9 10 11
# 赋予本机访问权限 grant select on test1.* to user1@'%' identified by 'UserPass123%';
# 赋予任意主机访问权限 grant select on test1.* to user1@'%' identified by 'UserPass123%';
# 赋予 ip为172.16.225.129 的主机访问权限 grant select on test1.* to user1@'172.16.225.129' identified by 'UserPass123%';
# 赋予 ip以172.16.225开头 的主机访问权限 grant select on test1.* to user1@'172.16.225.*' identified by 'UserPass123%';
grant 普通 DBA 管理某个 MySQL 数据库的权限
1
grant all privileges on test1.* to user1@localhost identified by 'UserPass123%';
grant 高级 DBA 管理 MySQL 中所有数据库的权限
1
grant all on *.* to dba@'localhost'
MySQL grant 权限,分别可以作用在多个层次上
grant 作用在整个 MySQL 服务器上:
1 2
grant select on *.* to dba@localhost ; -- dba 可以查询 MySQL 中所有数据库中的表。 grant all on *.* to dba@localhost ; -- dba 可以管理 MySQL 中的所有数据库
grant 作用在单个数据库上:
1
grant select on testdb.* to dba@localhost ; -- dba 可以查询 testdb 中的表。
grant 作用在单个数据表上:
1
grant select, insert, update, delete on testdb.orders to dba@localhost ;
grant 作用在表中的列上:
1
grant select(id, se, rank) on testdb.apache_log to dba@localhost ;
grant 作用在存储过程、函数上:
1 2
grant execute on procedure testdb.pr_add to 'dba'@'localhost' grant execute on function testdb.fn_add to 'dba'@'localhost'
查看 MySQL 用户权限 查看用户权限:
1 2 3 4 5
# 查看当前 MySQL 用户权限 show grants;
# 查看其他 MySQL 用户权限 show grants for dba@localhost;
撤销已经赋予给 MySQL 用户权限的权限
revoke 跟 grant 的语法差不多,只需要把关键字 “to” 换成 “from” 即可
1 2
grant all on *.* to dba@localhost; revoke all on *.* from dba@localhost;
如何刷新权限
1
flush privileges;
MySQL grant、revoke 用户权限注意事项
grant, revoke 用户权限后,该用户只有重新连接 MySQL 数据库,权限才能生效。
如果想让授权的用户,也可以将这些权限 grant 给其他用户,需要选项 “grant option“ grant select on testdb.* to dba@localhost with grant option; 这个特性一般用不到。实际中,数据库权限最好由 DBA 来统一管理。