一. 创建用户
CREATE USER 'username'@'host' IDENTIFIED BY 'password';
username:你将创建的用户名
host:指定该用户在哪个主机上可以登陆,从本地登录填localhost,任意主机登陆填通配符%
password:登陆密码,密码可以为空,如果为空则该用户可以不需要密码也可登陆
例如:
CREATE USER 'one'@'localhost' IDENTIFIED BY '123456';
CREATE USER 'one'@'192.168.1.101' IDENDIFIED BY '123456';
CREATE USER 'one'@'%' IDENTIFIED BY '123456';
CREATE USER 'one'@'%' IDENTIFIED BY '';
CREATE USER 'one'@'%';
二. 授权:
GRANT privileges ON databasename.tablename TO 'username'@'host'
说明:
privileges:用户的操作权限,如SELECT,INSERT,UPDATE等,如果要授予所的权限则使用ALL
databasename:数据库名,如果授予整个数据库权限填databasename.*
tablename:表名,如果要授予该用户对所有数据库和表的相应操作权限则可用*表示,如*.*
例子:
GRANT SELECT, INSERT ON test.user TO 'one'@'%';
GRANT SELECT, INSERT ON test.*TO 'one'@'%';
GRANT ALL ON *.* TO 'one'@'%';
用以上命令授权的用户不能给其它用户授权,如果想让该用户可以授权,用以下命令:
GRANT privileges ON databasename.tablename TO 'username'@'host' WITH GRANT OPTION;
三.设置与更改用户密码
SET PASSWORD FOR 'username'@'host' = PASSWORD('newpassword');
如果是当前登陆用户用:
SET PASSWORD = PASSWORD("newpassword");
例子:
SET PASSWORD FOR 'one'@'%' = PASSWORD("123456");
四. 撤销用户权限
REVOKE privilege ON databasename.tablename FROM 'username'@'host';
相关说明:
privilege, databasename, tablename:同授权部分
例子:
REVOKE SELECT ON *.* FROM 'one'@'%';
注意:
假如你在给用户'one'@'%'授权的时候是这样的(或类似的):
GRANT SELECT ON test.user TO 'one'@'%',
则在使用
REVOKE SELECT ON *.* FROM 'one'@'%';
命令并不能撤销该用户对test数据库中user表的SELECT 操作。
相反,如果授权使用的是
GRANT SELECT ON *.* TO 'one'@'%';
则
REVOKE SELECT ON test.user FROM 'one'@'%';
命令也不能撤销该用户对test数据库中user表的Select权限。
具体信息可以用如下查看。
SHOW GRANTS FOR 'one'@'%';
五.删除用户
DROP USER 'username'@'host';
六.遇到的问题
创建完成后用Navicat创建表遇到了报错:
Access denied; you need (at least one of) the PROCESS privilege(s)
根据提示是缺少PROCESS权限,赋予后问题解决
mysql> grant process on MyDB.* to test;
ERROR 1221 (HY000): Incorrect usage of DB GRANT and GLOBAL PRIVILEGES
第一次授予这样的权限,错误原因是process权限是一个全局权限,不可以指定在某一个库上(个人测试库为MyDB),所以,把授权语句更改为如下即可:
mysql> grant process on *.* to test;
Query OK, 0 rows affected (0.01 sec)
mysql> flush privileges;
Query OK, 0 rows affected (0.01 sec)
如果不给拥有授予PROESS权限 ,show processlist命令只能看到当前用户的线程,而授予了PROCESS权限后,使用show processlist就能看到所有用户的线程。官方文档的介绍如下:
SHOW PROCESSLIST shows you which threads are running.
You can also get this information from the INFORMATION_SCHEMA PROCESSLIST table
or the mysqladmin processlist command.
If you have the PROCESS privilege, you can see all threads. Otherwise,
you can see only your own threads (that is, threads associated with the
MySQL account that you are using). If you do not use the FULL keyword,
only the first 100 characters of each statement are shown in the Info field.