Docker MySql8 创建、删除、授权用户

发布时间 2023-04-13 14:51:41作者: Hexrui

1、登录MySql8

# 登录数据库
docker exec -it mysql8 mysql -uroot -proot123456

# 切换数据库实例
use mysql;

2、用户操作

2.1、查看用户

select host, user, authentication_string, plugin from user;

2.2、创建本地用户

# 创建一个用户名为admin,密码为 admin123456 的本地用户。
create user 'admin'@'localhost' identified by 'admin123456';

# 使admin用户获得所有权限
grant all privileges on *.* to 'admin'@'localhost';

# 刷新授权才会生效
flush privileges;

2.3、创建外网可访问用户

# 创建一个用户名为admin,密码为 admin123456 的本地用户
create user 'admin'@'%' identified by 'admin123456';

# 使admin用户获得所有权限
grant all privileges on *.* to 'admin'@'%';

# 刷新授权才会生效
flush privileges;

2.4、修改用户

# 查询用户信息
select * from user Where User='admin' and Host='localhost';

# 方式一:将用户名 admin 更新为 admin_newm
rename user 'admin'@'localhost' to 'admin_new'@'localhost';

# 方式二:将用户名 admin 更新为 admin_newm
update user set User='admin_new' where User='admin' and Host='localhost';

# 刷新授权才会生效
flush privileges;

2.5、删除用户

# 方式一:删除指定用户
drop user 'admin'@'localhost';

# 方式二:删除指定用户
delete from user Where User='admin' and Host='localhost';

# 刷新授权才会生效
flush privileges;

3、操作用户权限

3.1、查看用户权限

show grants for 'admin'@'localhost'; 

3.2、修改用户权限

# 使admin用户获得所有权限。
grant all privileges on *.* to 'admin'@'localhost';

# 使admin用户获得所有数据库中所有表的(*.*)select、insert、update、delete权限
grant select,insert,update,delete on *.* to 'admin'@'localhost';

# 如果只想让该用户访问某一个数据库写成:testdb.* 即可
grant all privileges on testdb.* to 'admin'@'localhost';

# 刷新授权才会生效
flush privileges;

3.3、删除用户权限

# 删除amdin用户在本地访问mysql时的所有权限
revoke all privileges on *.* from 'admin'@'localhost';

# 删除amdin用户在本地访问mysql时的insert和update权限
revoke insert,update on testdb.* from 'admin'@'localhost';

# 刷新授权才会生效
flush privileges;

4、修改密码

# 查询用户信息
select host, user, authentication_string, plugin from user;

# 需要先将authentication_string置空才能真正修改密码,否则会报错:ERROR 1396 (HY000)
update user set authentication_string='' where user='admin' and Host='localhost';
# 刷新授权才会生效
flush privileges;

# 修改admin用户的密码
ALTER USER 'admin'@'localhost' IDENTIFIED WITH MYSQL_NATIVE_PASSWORD BY 'admin123456';
# 刷新授权才会生效
flush privileges;