MySQL的权限管理分为两个验证阶段
- 检查是否允许连接,因为创建用户的时候会限制主机,是本地登陆,指定ip、指定ip段登陆还是任何主机都可以登陆
- 如果可以连接,会检查你发出的每个请求,查看你是否有权限进行操作,如查询某个表,修改某个表等
一、创建用户
命令
create user 'username'@'host' identified by 'password'
说明
- username:创建用户的用户名
- host:指定该用户可以从哪个主机上登陆,可以指定为localhost,指定ip,多个ip,或者%,
localhost表示只允许该用户本地登陆
%表示该用户可以从任何主机进行远程登陆
指定ip表示该用户只能从指定ip的主机进行远程登陆
- password:该用户对应的密码,可以设置为空
示例
create user 'johnhan'@'localhost' identified by 'johnhan'
create user 'johnhan'@'%' identified by 'johnhan'
create user 'johnhan'@'192.168.0.1' identified by 'johnhan'
create user 'johnhan'@'localhost' identified by ''
create user 'johnhan'@'localhost'
二、给用户授权
命令
grant privileges on databasename.tablename to 'username'@'host'
说明
- privileges:给该用户授予的权限,可以是select,update等,如果想授予全部权限,可是设置为all privileges
- on:指定权限是针对哪个数据库里的哪个表
- databasename:数据库名称
- tablename:表名称,如果想授予用户所有数据库和表的权限,可以用*.*表示
- to:将权限授予某个用户
示例
grant select,update privileges on test.user to 'johnhan'@'localhost'
grant all privileges on test.user to 'johnhan'@'localhost'
grant all privileges on *.* to 'johnhan'@'localhost'
grant all privileges on test.* to 'johnhan'@'localhost'
三、创建用户和授权可以用一条命令
grant all privileges on *.* to 'johnhan'@'localhost' identified by 'johnhan' with grant option
说明
- with grant option:表示该用户可以将自己所拥有的权限授予给别人
注意
- MySQL8之前的版本可以用一条命令,但是8不可用,8的版本需要先创建用户,在授权,也就是本文的一、二两步
四、刷新权限
flush privileges
- 对权限做了修改过后必须刷新权限才能生效
五、查看权限
查看当前用户权限
show grants
查看某位用户的权限
show grants for 'johnhan'@'localhost'
六、回收权限
revoke delete on *.* from 'johnhan'@'localhost'
七、删除用户
drop user 'johnhan'@'localhost'
八、更改用户名
rename user 'johnhan'@'localhost' to 'hh'@'localhost'
九、更改密码
- mysql8以下
1、set password命令
更改当前用户密码
set password = password('newpassword')
更改其他用户密码
set password for 'johnhan'@'localhost' = password('newpassword')
2、修改表
update user set password=password('newpassword') where user='username'
改完表需要刷新权限flush privileges
3、用mysqladmin
mysqladmin -u用户名 -p旧密码 password 新密码
- mysql8
alter user 'johnhan'@'localhost' identified by 'newpassword'