SQL語言:DDL、DML、DQL、DCL詳解
前言
SQL程序語言有四種類型,對數(shù)據(jù)庫的基本操作都屬于這四類,它們分別為;數(shù)據(jù)定義語言(DDL)、數(shù)據(jù)查詢語言(DQL)、數(shù)據(jù)操縱語言(DML)、數(shù)據(jù)控制語言(DCL)
數(shù)據(jù)定義語言(DDL)
DDL全稱是Data Definition Language,即數(shù)據(jù)定義語言,定義語言就是定義關系模式、刪除關系、修改關系模式以及創(chuàng)建數(shù)據(jù)庫中的各種對象,比如表、聚簇、索引、視圖、函數(shù)、存儲過程和觸發(fā)器等等。
數(shù)據(jù)定義語言是由SQL語言集中負責數(shù)據(jù)結構定義與數(shù)據(jù)庫對象定義的語言,并且由CREATE、ALTER、DROP和TRUNCATE四個語法組成。比如:
--創(chuàng)建一個student表
create table student(
id int identity(1,1) not null,
name varchar(20) null,
course varchar(20) null,
grade numeric null
)
--student表增加一個年齡字段
alter table student add age int NULL
--student表刪除年齡字段,刪除的字段前面需要加column,不然會報錯,而添加字段不需要加column
alter table student drop Column age
--刪除student表
drop table student --刪除表的數(shù)據(jù)和表的結構
truncate table student -- 只是清空表的數(shù)據(jù),,但并不刪除表的結構,student表還在只是數(shù)據(jù)為空
數(shù)據(jù)操縱語言(DML)
數(shù)據(jù)操縱語言全程是Data Manipulation Language,主要是進行插入元組、刪除元組、修改元組的操作。主要有insert、update、delete語法組成。
--向student表中插入數(shù)據(jù)
--數(shù)據(jù)庫插入數(shù)據(jù) 一次性插入多行多列 格式為INSERT INTO table (字段1, 字段2,字段3) VALUES (值1,值2,值3),(值1,值2,值3),...;
INSERT INTO student (name, course,grade) VALUES ('張飛','語文',90),('劉備','數(shù)學',70),('關羽','歷史',25),('張云','英語',13);
--更新關羽的成績
update student set grade='18' where name='關羽'
--關羽因為歷史成績太低,要退學,所以刪除關羽這個學生
delete from student where name='關羽'
數(shù)據(jù)查詢語言(DQL)
數(shù)據(jù)查詢語言全稱是Data Query Language,所以是用來進行數(shù)據(jù)庫中數(shù)據(jù)的查詢的,即最常用的select語句。
--從student表中查詢所有的數(shù)據(jù)
select * from student
--從student表中查詢姓名為張飛的學生
select * from student where name='張飛'
數(shù)據(jù)控制語言(DCL)
數(shù)據(jù)控制語言:Data Control Language。用來授權或回收訪問數(shù)據(jù)庫的某種特權,并控制數(shù)據(jù)庫操縱事務發(fā)生的時間及效果,能夠對數(shù)據(jù)庫進行監(jiān)視。
比如常見的授權、取消授權、回滾、提交等等操作。
1、創(chuàng)建用戶
語法結構:
CREATE USER 用戶名@地址 IDENTIFIED BY '密碼';
--創(chuàng)建一個testuser用戶,密碼111111
create user testuser@localhost identified by '111111';
2、給用戶授權
語法結構:
GRANT 權限1, … , 權限n ON 數(shù)據(jù)庫.對象 TO 用戶名;
--將test數(shù)據(jù)庫中所有對象(表、視圖、存儲過程,觸發(fā)器等。*表示所有對象)的create,alter,drop,insert,update,delete,select賦給testuser用戶
grant create,alter,drop,insert,update,delete,select on test.* to testuser@localhost;
3、撤銷授權
語法結構:
REVOKE權限1, … , 權限n ON 數(shù)據(jù)庫.對象 FORM 用戶名;
--將test數(shù)據(jù)庫中所有對象的create,alter,drop權限撤銷
revoke create,alter,drop on test.* to testuser@localhost;
4、查看用戶權限
語法結構:
SHOW GRANTS FOR 用戶名;
--查看testuser的用戶權限
show grants for testuser@localhost;
5、刪除用戶
語法結構:
DROP USER 用戶名;
--刪除testuser用戶
drop user testuser@localhost;
6、修改用戶密碼
語法結構:
USE mysql;
UPDATE USER SET PASSWORD=PASSWORD(‘密碼’) WHERE User=’用戶名’ and Host=’IP’;
FLUSH PRIVILEGES;
--將testuser的密碼改為123456
update user set password=password('123456') where user='testuser' and host=’localhost’;
FLUSH PRIVILEGES;
結尾
本文對SQL程序語言有四種操作語言做了一個簡單的介紹和概括,對數(shù)據(jù)庫的基本操作都屬于這四類,它們分別為;數(shù)據(jù)定義語言(DDL)、數(shù)據(jù)查詢語言(DQL)、數(shù)據(jù)操縱語言(DML)、數(shù)據(jù)控制語言(DCL) 。