資料庫中常用的對字段的操作

2021-08-19 05:45:20 字數 3472 閱讀 5282

1.增加字段

alter table 表名 add 欄位名稱  字段型別
alter table course add tid int;   --在課程表中增加教師編號tid欄位
alter table 表名 add (欄位名稱  字段型別,欄位名稱  字段型別.....);  --增加多個字段
2.修改字段

(1)修改欄位的名稱

alter table 表名 rename  column 原欄位名  to 新欄位名;
alter table stu rename column sid to zid;  --將學生表中的sid欄位重新命名為zid
(2)修改欄位的型別和長度

alter table 表名  modify (欄位名稱  (新的)字段型別或者新的長度);
alter table sc add mim int;  --在成績表中增加一列mim
alter table sc modify(mim varchar(10));   --修改mim欄位的資料型別
alter table sc modify(mim varchar(30));  --修改mim欄位的長度,當此列有資料時,不能將字段的長度減小,只能增加長度
3.刪除字段

alter table 表名 drop column 欄位名;
alter table sc drop column mim;   --刪除成績表中的字段mim
4.新增約束

六大約束

1.—-主鍵約束(primay key coustraint) 唯一性,非空性

2.—-唯一約束 (unique counstraint)唯一性,可以空,但只能有乙個

3.—-檢查約束 (check counstraint) 對該列資料的範圍、格式的限制(如:年齡、性別等)

4.—-預設約束 (default counstraint) 該資料的預設值

5.—-外來鍵約束 (foreign key counstraint) 需要建立兩表間的關係並引用主表的列

6.--非空約束(not null constraint) 字段內容不能為空

(1)在建表時新增約束

create table stu( 

id number, 

--學生姓名,不能為空,不能重複 

name varchar2(20) not null unique, 

--學生姓名只能是male或female 

*** varchar2(6) not null check(***='male' or ***='female'),

--學生年齡只能在18到60之間 

age number check(age >18 and age <60), 

--郵箱可以不填寫,填寫的話不能相同 

email varchar2(30) unique, 

address varchar2(30) default '湖南懷化', 

--外來鍵約束 

cid int not null references c(cid)  

);

(2)建立字段約束

a.建立主鍵約束

alter table 表名

add constraints 約束名 primary key(欄位名);

--為表增加主鍵約束 

alter table stu

add constraints pk_id primary key(id);

b.建立外來鍵約束

alter table 表名

add constraints 約束名 foreign key(欄位名) references 引用表的表名(相應的欄位名);

alter table c add constraint fk_tid foreign key(tid) references teacher(tid)  --在課程表中建立外來鍵tid
c.建立唯一約束

alter table 表名

add constraints 約束名 unique(欄位名);

alter table stu 

add constraints name_unique unique(name); --姓名不能重複

d.新增檢查約束

alter table 表名 

add constraints 約束名 check(檢查條件);

--新增檢查約束 

alter table stu

add constraints check_age check(che_age>18 and che_age<60);

e.建立非空約束

alter table 表名 modify 欄位名 not null;
alter table stu modify name not null;
f.建立預設約束

alter table 表名 modify 欄位名 default 預設值;
alter table stu modify address default '湖南懷化'
(2)刪除約束

--刪除主鍵約束 

alter table 表名

drop constraints 約束名;

--刪除主鍵約束 

alter table stu

drop constraints age_check;

(3)禁用約束

--禁用約束 

alter table 表名 disable constraints 約束名;

--禁用約束 

alter table stu disable constraints age_check;

(4)啟用約束

--啟用約束 

alter table 表名 enable constraints 約束名;

--起用約束 

alter table stu enable constraints age_check;

資料庫中常用的操作語句

1.顯示資料庫列表 show databases 用於可檢視你當前一共有多少個資料庫!2.使其成為當前運算元據庫 use mysql 開啟資料庫.選擇進入你想進入的資料庫 show tables 顯示mysql資料庫中的資料表.顯示的是你輸入的資料庫當中的所有表 3.顯示資料表的表結構 descri...

Qt中常用的資料庫操作

簡述 常用的資料庫操作主要有查詢 插入 刪除等 qsqldatabase建立連線資料庫例項,乙個qsqldatabase的例項代表乙個資料庫的連線。qt 提供了對不同資料庫的驅動支援 driver type description qdb2 ibm db2 qibase borland interb...

golang 對mysql資料庫的常用操作

匯入包 連線資料 db,err sql.open mysql root 123456789 mydb?charset utf8 if err nil查詢資料 var id int var username,password string rows,err db.query select from m...