创建数据库/表,向表中插入数据
如果数据库不存在则创建,存在则不创建(if not exists),也可以省略不会报错。 创建testdate数据库,并设定编码集为utf8
#创建数据库testdate;
create database if not exists test02 default charset utf8 collate utf8_general_ci;
删除数据库 drop database ;
#删除数据库test01drop 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 tablegrade_table(
g_idint(10) not nullauto_increment,
snamevarchar(10) not null,
gardeint(10) not null,
rankvarchar(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 ;drop table`grade_table`;
#使用truncate 清空数据表不会进行删除操作truncate table students;
向表中插入数据
#插入数据语法:insert into 表名(列1,列2,列3,。。。,列n)values(value1,value2,。。。valuen),...,(。。。);
#在students表中插入三行数据insert intostudents (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 intograde_table(g_id,sname,garde,rank)values(8,'小明',70,'B'),
(7,'小郑',90,'A'),
(10,'小红',60,'C');
students表:
grade_table表