使用Grant创建新用户
## 创建无任何权限的用户,all代表赋予所有权限,也可以指定具体权限(select、update等)
grant usage on *.* to 'user2'@'localhost' identified by '123456' with grant option;
- on:表示对哪些数据库以及哪些数据表生效,*.*代表所有数据库下的所有数据表,也可以指定如‘’test.mytable’
- to:表示将权限赋予哪个用户,‘username’@‘host’
username指将创建的用户名;host指该用户在哪个主机上可以登录,如localhost是本地用户,%是通配符,可以单独写也可以像这样写’192.168.1.%’ - identified by:指定用户的登录密码
注意:使用Grant创建用户时,密码会进行自动加密 - with grant option:表示用户可以将权限传递给其他用户
- 比如这里user2可以
grant select on *.\* to user3
但如果没有写with grant option,用户user就无法给user3授权
使用GRANT给用户添加权限,权限会自动叠加,不会覆盖之前授予的权限,比如你先给用户添加一个SELECT权限,后来又给用户添加了一个INSERT权限,那么该用户就同时拥有了SELECT和INSERT权限。
查看权限
## 第一种方式:直接查表
select * from mysql.user;
## 第二种方式
## 查看当前登录用户的权限
show grants;
## 指定用户
show grants for 'user2'@'localhost';
使用insert语句直接向mysql.user表里插入新用户
## 创建的新用户没有任何权限
insert into mysql.user (user,host,password,ssl_cipher,x509_issuer,x509_subject) values ('user3','localhost','123456','','','');
注意:使用这种方法创建的用户密码是明文的,而在登录连接时,mysql认为密码需要先加密,所以是登录不上去的,解决方法有以下两种
## 第一种方式:在insert时就将密码加密
insert into mysql.user (user,host,password,ssl_cipher,x509_issuer,x509_subject) values ('user3','localhost',password('123456'),'','','');
## 第二种方式:创建明文密码之后进行修改
update mysql.user set password=password('123456') where user='user3';
flush privileges;
注意用insert方式创建用户后必须刷新权限,这是为了告诉服务器重读授权表。否则,只有重启服务器后更改方会被注意到。
MySQL5.7密码list中password变了为authentication_string
使用 CREATE USER创建新用户
create user 'username'@'host' identified by 'password'
删除用户和撤销权限
## 删除用户
drop user user2;
drop user user2@localhost;
## 撤销权限
revoke all on *.* from 'user2'@'localhost';
修改已存在用户密码
## 修改当前登录用户密码
set password = password('newpwd');
## 修改指定用户密码
set password for username@host=password('newpwd');
## 使用grant修改密码
grant all on *.* to user2@localhost identified by 'newpwd';
## 直接update mysql.user表,然后flush privileges;(不推荐)
update mysql.user set password=password('newpwd') where host='host' and user='username'
flush privileges;
## 使用mysqladmin
mysqladmin -uusername -poldpwd password newpwd