3、用户管理语句

_ 表示任意单个字符

% 表示任意长度的任意字符

查询用户

#切换到mysql库,查询user表,得到当前库的用户名和其能够远程登录时所在的host
> use mysql;
> select user,host,password from user;

创建用户

1. 方法一
> create user 'kcxg'@'127.0.0.1';
> create user 'kcxg'@'127.0.0.1' identified by '123456';
2. 方法二(使用较少,设置严格的sql-mode后,无法使用)
> insert into mysql.user(user,host,password) values('kcxg','192.168.%.%',password('123456'));
3.方法三(在授权数据库时,用户不存在将会自动创建)
> grant all on  cuiyk.* to kcxg@127.0.0.1 identified by '123456'

删除用户

1. 方法一(使用此方法会有相关信息残留)
> delete from mysql.user where user='kcxg' and host='localhost';
2. 方法二
> drop user kcxg@localhost;

重命名用户

> rename user oldname to newname;

修改密码

1.方法一
> mysqladmin -u用户名 -p旧密码 password 新密码
2.方法二
> set password for kcxg@host = password('newpassword');
3.方法三
适用mysql5.6以及之前的版本
>update mysql.user set password = password('密码') where user='用户名';
适用mysql5.7
> update mysql.user set authentication_string = password('密码') where user='用户名';
4.方法四(重置root密码)
- [1] 停止当前mysql进程
- [2] mysqld_safe --skip-grant-tables &
- [3] mysql -uroot
- [4] mysql> UPDATE mysql.user SET password=PASSWORD("new password") WHERE user='root';
- [5] mysql> FLUSH PRIVILEGES;
- [6] 停止数据库以后,按照正常的方式重启数据库,使用新密码登录即可

授权管理

授权命令

> GRANT ALL [PRIVILEGES] ON db.tbl TO 'username'@'host' IDENTIFIED BY 'password';
#给本地用户授权某个数据库的所有权限
> grant all privileges on zsythink.* to zsy@localhost identified by 'zsythink';
#给远程用户授权
> grant all privileges on zsythink.* to zsy@'%' identified  by  'zsythink';
> FLUSH PRIVILEGES
#授权某些权限
> grant select privileges on zsythink.* to zsy@'192.168.%.%';
> grant insert,delete,update,select on zsythink.* to zsy@'192.168.%.%';
#授权于多个用户
> grant select on hellodb.* to zsy@localhost,zsythink@localhost;
#只对某张表的某个字段授权
> grant select (name,age) on zsythink.students to zsy@localhost;
#function指明被操作对象为函数
> grant execute on function zsythink.test to zsy@'192.168.%.%';
#procedure 指明备操作的对象为存储过程
> grant execute on procedure zsythink.test to zsy@'192.168.%.%';
#usage权限用于登录用户
> grant usage on *.* to 'zsy'@'222.222.222.222' require ssl;
> grant usage on *.* to 'zsy'@'222.222.222.222' require none;
#如果在授权zsy用户时,搭配grant选项,则zsy用户有权将拥有的用户授予其他用户
> grant select on zsythink.* to zsy@'192.168.%.%'  with grant option;

MAX_QUERIES_PER_HOUR:限制用户每小时执行的查询语句数量
MAX_UPDATES_PER_HOUR:限制用户每小时执行的更新语句数量
MAX_CONNECTIONS_PER_HOUR:限制用户每小时连接数据库的次数
MAX_USER_CONNECTIONS:限制用户使用当前账号同时连接服务器的连接数量
> grant select on *.* to zsy@'192.168.%.%' identified by '123456' with MAX_QUERIES_PER_HOUR 20;

查看授权

> show grants for 用户名;
> show grants for zsy@localhost
> select * from mysql.db where Db="你要查看的数据库"

删除授权

> revoke "要移除的权限" on 数据库.表 from 用户@host;
原文地址:https://www.cnblogs.com/kcxg/p/10357920.html