Mysql 创建用户与授权

1. 创建用户:

CREATE USER 'username'@'host' [IDENTIFIED BY 'password'];

username:要创建的用户名;
host:代表地址;任何地址可以使用%
IDENTIFIED BY 'password':设置密码,如果不写则为空密码

eg:

CREATE USER 'root'@'localhost' IDENTIFIED BY '123';
CREATE USER 'root'@'%' IDENTIFIED BY '123';

2、授权:

GRANT privileges ON dbName.tableName TO 'username'@'host' [WITH GRANT OPTION];

privileges:用户的操作权限,如select, delete, update等,共14个。
dbname:数据库名
tablename:表名
WITH GRANT OPTION: 被授权的用户可以将他的拥有的权限授给其他用户
若要授权用户对所有数据库和表的相应操作权限可以用*表示,如*.*。

eg:

1. 查询、插入、更新、删除 数据库中所有表数据的权利。
grant select on testdb.* to common_user@'%'
grant insert on testdb.* to common_user@'%'
grant update on testdb.* to common_user@'%'
grant delete on testdb.* to common_user@'%'
grant select, insert, update, delete on testdb.* to common_user@'%'

2. 创建表、索引、视图、存储过程、函数等权限。
grant create on testdb.* to developer@'192.168.0.%';
grant alter on testdb.* to developer@'192.168.0.%';
grant drop on testdb.* to developer@'192.168.0.%';

3. 操作外键权限。
grant references on testdb.* to developer@'192.168.0.%';

4. 操作临时表权限。
grant create temporary tables on testdb.* to developer@'192.168.0.%';

5. 操作索引权限。
grant index on testdb.* to developer@'192.168.0.%';
 
6. 操作视图、查看视图源代码权限
grant create view on testdb.* to developer@'192.168.0.%';
grant show view on testdb.* to developer@'192.168.0.%';

7. 操作存储过程、函数 权限
grant create routine on testdb.* to developer@'192.168.0.%'; -- now, can show procedure status
grant alter routine on testdb.* to developer@'192.168.0.%'; -- now, you can drop a procedure
grant execute on testdb.* to developer@'192.168.0.%';
 
8. 管理数据库的权限。
grant all privileges on testdb to dba@'localhost'
其中,关键字 “privileges” 可以省略

9. 管理所有数据库的权限。
grant all on *.* to dba@'localhost'


查看当前用户(自己)权限:
show grants;
 
查看其他用户权限:
show grants for dba@localhost;

刷新授权,使之立即生效
flush privileges; 

3、撤销用户权限

REVOKE privilege ON dbname.tablename FROM 'username'@'host';

revoke 跟 grant 的语法差不多,只需要把关键字 “to” 换成 “from” 即可:

grant all on *.* to dba@localhost;
revoke all on *.* from dba@localhost;

4、设置和更改用户密码

SET PASSWORD FOR 'username'@'host'=PASSWORD('your_password');
alter user 'username'@'host' identified by 'your_password';

5、删除用户:

DROP USER 'username'@'host';

 

Logo

更多推荐