适用版本:MySQL 5.x 系列
说明:所有命令以 ; 结尾,-- 后为注释
符号说明
•
%:允许所有非本地主机登录(不含 localhost)
•
%:替换为 IP,即只允许该 IP 登录
•
localhost:仅允许本地主机登录
•
*:代表所有数据库 / 所有表
一、新建用户
1.
以 root 登录 MySQL(命令行)
2.
创建本地登录用户
|
sql
mysql>
insert into mysql.user(Host,User,Password)
values("localhost","test",password("1234"));
|
3.
创建远程任意主机登录用户
|
sql
mysql>
insert into mysql.user(Host,User,Password)
values("%","test",password("1234"));
|
4.
创建指定 IP 远程登录用户
|
sql
mysql>
insert into mysql.user(Host,User,Password)
values("192.168.8.1","test",password("1234"));
|
5.
验证登录(命令行)
|
Plain Text
exit
mysql -u test -p
|
二、为用户授权
授权格式
|
sql
grant
权限 on 数据库名.表名 to 用户名@登录主机 identified by "密码";
flush privileges;
|
常用授权示例
1.
授予某数据库所有权限(推荐)
|
sql
mysql>
create database testDB; -- 创建测试数据库
mysql> grant all privileges on testDB.* to test@localhost identified by
'1234'; -- 给本地test用户全部权限
mysql> flush privileges; -- 刷新权限生效
|
2.
授予某数据库部分权限
|
sql
mysql>
grant select,update on testDB.* to test@localhost identified by '1234';
mysql> flush privileges;
|
3.
授予所有数据库部分权限
|
sql
mysql>
grant select,delete,update,create,drop on *.* to test@"%"
identified by "1234";
mysql> flush privileges;
|
三、取消授权
取消授权格式
|
sql
REVOKE
权限 on 数据库名.表名 from 用户名@登录主机;
|
常用取消示例
1.
取消某数据库所有权限
|
sql
mysql>
REVOKE all on testDB.* from test@'%';
|
2.
取消指定权限
|
sql
mysql>
REVOKE update,delete on testDB.* from test@'%';
|
3.
取消某表指定权限
|
sql
mysql>
REVOKE update,delete on testDB.table11 from test@'%';
|
四、删除用户
方法一(推荐,安全简单)
|
sql
mysql>
drop user 用户名@'%'; -- 删除允许远程登录的用户
mysql> drop user 用户名@localhost; -- 删除本地登录的用户
mysql> drop database testDB; -- 删除用户数据库(按需执行)
|
方法二(老方法,不推荐)
|
sql
mysql>
delete FROM user Where User='test' and Host='localhost';
mysql> delete FROM user Where User='test' and Host='%';
mysql> flush privileges;
mysql> drop database testDB;
|
五、修改用户密码
方法一(推荐,标准写法)
|
sql
mysql>
set password for '用户名'@'%' = password('新密码'); -- 修改远程用户密码
mysql> set password for '用户名'@'localhost' =
password('新密码'); -- 修改本地用户密码
mysql> flush privileges;
|
方法二(老方法,不推荐)
|
sql
mysql>
update mysql.user set password=password('新密码') where
User="用户名" and Host="localhost";
mysql> update mysql.user set password=password('新密码') where User="用户名" and
Host="%";
mysql> flush privileges;
|