MySql用户管理

8.0版本

一、Mysql查看用户

查看所有用户:select user,host from mysql.user;

1
2
3
4
5
6
7
8
9
10
11
12
+------------------+-------------+
| user | host |
+------------------+-------------+
| push_deer | 192.168.0.% |
| debian-sys-maint | localhost |
| mysql.infoschema | localhost |
| mysql.session | localhost |
| mysql.sys | localhost |
| root | localhost |
+------------------+-------------+
6 rows in set (0.00 sec)

二、Mysql创建用户

语法:

1
CREATE USER 'username'@'host' IDENTIFIED BY 'password';

解释:

  • username:登陆用户名
  • host:指定可访问的地址
    • 本机:localhost
    • 通配符形式:192.168.0.%
    • 全部:%
  • password:登陆密码,如果密码为空则无需密码

三 、Mysql删除用户

  1. 选择删除的用户:select user,host from mysql.user
  2. 删除用户:drop user 'test'@'%';

四、Mysql修改设置用户密码

ALTER USER 'test'@'%' IDENTIFIED BY 'new_password';

五、Mysql用户授权 && 撤销授权

🚡会修改mysql.user表,grant, revoke 用户权限后,该用户只有重新连接 MySQL 数据库,权限才能生效。

5.1、授权GRANT

语法:
1
grant privileges on database.tablename to “username”@‘host’;

说明:
- privileges:用户的操作权限,如SELECTINSERTUPDATE等,如果要授予所的权限则使用ALL

  • database
    • 不指定数据库:*.*
    • 如果指定数据库但不指定表名:db.*
    • 指定库和表名:db.tableName
  • username:登陆的用户名
  • host:可访问的主机IP
    • 本机:localhost
    • 通配符形式:192.168.0.%
    • 全部:%>)
      实例:
      创建用户对于test库所有表的select,insert,update,delete,create,drop权限
      1
      grant select,insert,update,delete,create,drop on test.* to 'test'@'%' ;

创建用户reader对所有库只读权限

1
grant select on *.* to 'reader'@'%'  identified by '123456';

创建用户testd对test库的test_tb表赋予select权限

1
grant select on test.test_tb to 'test'@'%' ;

5.2、撤销授权Revoke

撤销(revoke)的和授予(grant)的基本一样,除了revoke(对应grant)和from(对应to

语法:

1
revoke privileges on database.tablename from 'username'@'host';

5.3、密码过期和锁定用户

在MySQL5.6.6版本起,增加了password_expired功能,它允许设置MySQL数据库用户的密码过期时间。这个特性已经添加到mysql.user数据表,它的默认值是”N”,表示已禁用密码过期功能

1
2
3
4
5
6
7
8
9
10
11
12
13
14
select user,password_expired from musql.user;
<mysql%3E select user,password_expired from mysql.user;
+------------------+------------------+
| user | password_expired |
+------------------+------------------+
| push_deer | N |
| test | N |
| debian-sys-maint | N |
| mysql.infoschema | N |
| mysql.session | N |
| mysql.sys | N |
| root | N |
+------------------+------------------+
7 rows in set (0.00 sec)

设置密码过期:

1
2
3
方法一: alter user 'test'@'%' password expire;
方法二: update mysql.user set password_expired='Y' where user = 'test';
flush privileges;

撤销过期:

1
2
update mysql.user set password_expired='N' where user = 'test';
flush privileges;

创建用户后锁定用户:

1
2
create user 'test'@'%' identified by 'password' account lock;
flush privileges;

解锁 :

1
2
alter user 'test'@'%' account unlock;
flush privileges;

任意时刻加锁:

1
alter user 'test'@'%' account lock;

附录

权限列表

常见权限