首页 > 代码库 > 详解MySQL第三篇—DCL语句

详解MySQL第三篇—DCL语句

DCL(Data Control Language)语句:数据控制语句,用于控制不同数据段直接的许可和访问级别的语句。这些语句定义了数据库、表、字段、用户的访问权限和安全级别。主要的语句关键字包括 grant、revoke 等。

DCL 语句主要是 DBA 用来管理系统中的对象权限时所使用,一般的开发人员很少使用。下面通过一个例子来简单说明一下。

创建一个数据库用户 z1,具有对 sakila 数据库中所有表的 SELECT/INSERT 权限:

 

 
1
2
3
4
5
6
7
8
9
10
11
12
mysql> grant select,insert on sakila.* to ‘z1‘@‘localhost‘ identified by ‘123‘;
Query OK, 0 rows affected (0.00 sec)
mysql> exit
Bye
[mysql@db3 ~]$ mysql -uz1 -p123
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 21671 to server version: 5.1.9-beta-log
Type ‘help;‘ or ‘\h‘ for help. Type ‘\c‘ to clear the buffer.
mysql> use sakila
Database changed
mysql> insert into emp values(‘bzshen‘,‘2005-04-01‘,3000,‘3‘);
Query OK, 1 row affected (0.04 sec)

 

由于权限变更,需要将 z1 的权限变更,收回 INSERT,只能对数据进行 SELECT 操作:

 

 
1
2
3
4
5
6
7
8
[mysql@db3 ~]$ mysql -uroot
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 21757 to server version: 5.1.9-beta-log
Type ‘help;‘ or ‘\h‘ for help. Type ‘\c‘ to clear the buffer.
mysql> revoke insert on sakila.* from ‘z1‘@‘localhost‘;
Query OK, 0 rows affected (0.00 sec)
mysql> exit
Bye

 

用户 z1 重新登录后执行前面语句:

 

 
1
2
3
4
5
6
7
8
9
10
[mysql@db3 ~]$ mysql -uz1 -p123
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 21763 to server version: 5.1.9-beta-log
Type ‘help;‘ or ‘\h‘ for help. Type ‘\c‘ to clear the buffer.
mysql> insert into emp values(‘bzshen‘,‘2005-04-01‘,3000,‘3‘);
ERROR 1046 (3D000): No database selected
mysql> use sakila
Database changed
mysql> insert into emp values(‘bzshen‘,‘2005-04-01‘,3000,‘3‘);
ERROR 1142 (42000): INSERT command denied to user ‘z1‘@‘localhost‘ for table ‘emp‘

 

以上例子中的 grant 和 revoke 分别授出和收回了用户 z1 的部分权限,达到了我们的目的。

详解MySQL第三篇—DCL语句