一,DDL操作 對數據庫中的某些對象(例如,database,table)進行管理,如Create,Alter和Drop.
1.操作數據庫
--創建數據庫
create database if not exists dbname;
--銷毀數據庫
drop databasae if exists dbname;
2.操作數據庫表
2.1 添加字段
--追加字段
alter table tname add 字段名稱 類型(長度);、
--添加字段到第1列
alter table tname add 字段名稱 類型(長度) first;
--添加字段到指定列后面
alter table tname add 字段名稱 類型(長度) after 指定列名;
2.2刪除字段
alter table tname drop 字段名稱;
2.3修改字段:名稱,類型,長度,約束描述等
alter table tname modify 字段名稱 新類型 新約束;
alter table tname change 舊字段名 新字段名 新類型 新約束;
2.4修改表名
rename table tname to new_tname;
2.5刪除數據庫表
drop table tname;
二,DML操作 對數據庫中的數據進行一些簡單操作,如insert,delete,update,select等.
1.insert
1.1 語法格式
insert into tname[(fie1,fie2,...)] values(val1,val2,...);
1.2 單條插入
#插入一條完整的記錄:值的順序要和表中字段的順序保持一致
insert into stu values('haha@163.com', 'zs', 18, '男', '13211111111');
#插入記錄:ls 20 女,聲明字段的順序可以任意,值的順序與聲明的字段的順序保持一致
insert into stu(sname, age, sex) values('ls', 20, '女');
1.3 批量插入
#插入3條記錄(批量插入):ww 23 男 zl 34 男 haha 24 女,效率高,因為I/O操作少。
insert into stu(sname, age, sex) values('ls', 20, '男'),('zl', 34, '男'),('haha', 20, '女');
1.4復制表
#復制表:stu表 -> student表。思路:1.創建student表,結構類似(結構復制);2.查詢stu表插入到student表中。
方法一:
select * from stu where 1=0;#一條數據也沒查到,因為條件不成立,但是結果集中是有表結構的
create table student select * from stu where 1=0;#復制表結構
insert into student select * from stu;#查詢並插入數據
方法二:
create table stu1 select * from stu;#復制表結構及其數據
1.5 插入日期
alter table stu add bir date;#添加字段
insert int stu values('hehe', 20, '男', '13211111111', '1996-06-06');#'1996-06-06' 是字符串
2.delete
語法格式:
delete from tname [where condition];
實例代碼:
delete from stu where sname='haha';
3.update
語法格式:
update tname set fie1 = val1, fie2=val2,... [where condition]
實例代碼:
update stu set age=28 where sname='zs';#where后的條件字段必須唯一確定該條記錄:主鍵