MySQL 8.x 账号管理
MySQL 8.x 和MySQL 5.x 创建账号不太一样,MySQL 8 开始不允许用grant带密码创建账号了,要先创建账号再设置权限
MySQL 8.x
# 创建账号
create user "root"@"%" identified by "xxx";
# 授权
grant all privileges on *.* to "root"@"%" with grant option;(执行该命令也可以直接创建账号)
# 刷新权限
flush privileges;
# 修改密码加密方式(MySQL 8 默认用 caching_sha2_password 插件加密密码)
alter user root identified with mysql_native_password by "xxx";
# 注意不能用以下update的方式直接修改加密插件,不同的插件,加密的密码不一样,只修改加密插件,不修改或者重新创建密码会导致MySQL连接不了
update mysql.user set plugin="mysql_native_password" where user="root";
MySQL 5.x
# 创建账号并授权
grant all privileges on *.* to root@"%" identified by "xxx" with grant option;
下面以test账号为例,记录常用命令(在MySQL 8.0.25操作)
授权test用户拥有所有数据库的某些权限
create user "test"@"localhost" identified by "xxx";
grant select,delete,update,create,drop on *.* to test@"localhost";
修改指定用户密码
alter user "test"@"localhost" identified by "123";
# 指定密码认证插件
alter user "test"@"localhost" identified with mysql_native_password by "123";
# 设置密码后,记得刷新权限
flush privileges;
或者
mysqladmin -u root -p password 123
回车之后会要求让输入原始密码
# 注意,不能用以下SQL修改密码,原因:MySQL 5.7.9 之后取消了password 函数,authentication_string=password("xxx") 会报错
update mysql.user set authentication_string=password("xxx") where user="test" and host="localhost";
删除用户
delete from mysql.user where user="test" and host="localhost";
或者
drop user "test"@"localhost";
查看权限
# 查看当前用户权限
show grants;
# 查看其他 MySQL 用户权限
show grants for "test"@localhost;
撤销已经赋予给 MySQL 用户权限的权限
revoke 跟 grant 的语法差不多,只需要把关键字 to 换成 from 即可:
grant all on *.* to "test"@"localhost";
revoke all on *.* from "test"@"localhost";