創建數據庫/表,向表中插入數據
如果數據庫不存在則創建,存在則不創建(if not exists),也可以省略不會報錯。 創建testdate數據庫,並設定編碼集為utf8
#創建數據庫testdate;
create database if not exists test02 default charset utf8 collate utf8_general_ci;
刪除數據庫 drop database <數據庫名>;
#刪除數據庫test01 drop database test01;
#在表中添加規則
primary key #標識該字段為該表的主鍵,可以唯一的標識記錄,主鍵就是不為空且唯一當然其還有加速查詢的作用
foreign key #標識該字段為該表的外鍵,用來建立表與表的關聯關系
not null #標識該字段不能為空
unique key #標識該字段的值是唯一的
auto_increment #標識該字段的值自動增長(整數類型,而且為主鍵)
default #為該字段設置默認值
unsigned #將整型設置為無符號即正數
zerofill #不夠使用0進行填充
#創建表語法 create table table01("屬性" 數據類型 not noll,...) engine=innodb default charset=utf8;不想字段為 NULL 可以設置字段的屬性為 NOT NULL
#AUTO_INCREMENT定義列為自增的屬性,一般用於主鍵,數值會自動加1
#其中字段加 ·· (反引號esc下面的按鍵)是為了區分關鍵字 也可以不用加,也可以運行成功
#其中設置 id(要唯一,不能重復) (primary key主鍵,auto_increment自增)
#創建students,以id為主鍵 create table `students`( `id` int(10) not null auto_increment primary key, `snames` varchar(10) not null, `班級` varchar(10) not null, `出生日期` date )engine=innodb default charset=utf8; #創建成績表grade_table,關聯students表中外鍵 create table grade_table( g_id int(10) not null auto_increment, sname varchar(10) not null, garde int(10) not null, rank varchar(10) not null, constraint fk_id foreign key (g_id) references students(id)
on update cascade #更新同步
on delete cascade #刪除同步
)engine=innodb default charset=utf8;; #fk_id 為外鍵約束索引,外鍵名稱為 g_id,其依賴於表 students 的主鍵 id。
#刪除數據表:drop table <table_name>; drop table `grade_table`; #使用truncate 清空數據表不會進行刪除操作 truncate table students;
向表中插入數據
#插入數據語法:insert into 表名(列1,列2,列3,。。。,列n)values(value1,value2,。。。valuen),...,(。。。); #在students表中插入三行數據 insert into students (id,snames,班級,出生日期) values (8,'小明','一班','2010-12-08'), (7,'小鄭','二班','2008-06-18'), (10,'小紅','三班','2009-11-08');
#所有列進行添加數據的話,可不用把所有列寫出來;如下在students表中搽插入id=12的一行數據
#在students中插入一行數據,注意id不能有重復 insert into students values (12,'小藍','三班','2011-10-08');
#在grade_table表中插入三行數據
insert into grade_table(g_id,sname,garde,rank) values (8,'小明',70,'B'), (7,'小鄭',90,'A'), (10,'小紅',60,'C');
students表:

grade_table表

