二、数据库中表的操作
0.mysql数据库中的数据类型
1.增加表
CREATE TABLE 表名
(
字段名1,数据类型[完整性约束条件],
字段名2,数据类型[完整性约束条件],
......
字段名n,数据类型[完整性约束条件],
)
//创建表之间一定先连接一个数据库!
~创建一张学生表student
create table student
(
xh char(12),
name char(12),
sex char(5),
age int
);
2.查看表
查看表结构:desc 表名;
查询当前数据库中的所有表:show tables;
查看表的建表语句:show create table 表名;
3.修改表(ALTER TABLE语句)
~添加新的字段(列)
alter table book1 add xb char(3)//如果同时添加多个字段ADD后加括号
~修改字段属性
Alter table +表名 modify xh char(12);
~删除字段
Alter table +biaoming drop bj;
~修改表名
Alter tablr+biaoming rename 新表名;
~修改列名
Alter table +biaoming change uname username char(12);
4.删除表
DROP TABLE 表名;
二、表的约束
1.单字段主键
create table student
(
xh char(12) PRIMARY KEY,
name char(12),
sex char(5),
age int
);
2.多字段主键
create table book3
(
ID int,
name char(8) not null, //not null为非空约束
sex char(3) default '男',
ISBN char(20),
PRIMARY KEY(ID,ISBN)
);
3.字段值自动增加
create table book1
(
ID int auto_increment,
name char(20) not null,
shuhao int
);
create table student
(
xh char(12),
name char(12),
sex char(5),
age int
);
第三章 添加、更新与删除数据
1.插入数据
insert into student(xh,name,sex,age,sdept)
values("201711059","吴乐娟","女","19","计科")
~可省略INTO
insert student (xh,name,sex,age,sdept)
values("2017110001","韩旭","女","19","计科")
~可省略各列名,但数据必须11对应
insert student values("201713031","徐佳莹","女",”20”,"计科")
~一次添加多个数据
insert student values("201713015","邢家瑞","女",19,"计科"),
("201713042","谷聪","女",19,"计科"),
("201713043","赵晶","女",19,"计科")
2.修改数据(UPDATA)
UPDATE 表名
SET 字段名1 = 值1[,字段名2 = 值2,……][WHERE 更新条件]
~无条件时,全部有效
update student set age=18 where name="吴乐娟"
~修改多项,用逗号分隔
update student set age=16,sex="男" where name="谷聪"
3.删除数据(DELETE)(truncate)
DELETE FROM 表名 [WHERE 条件表达式]
~ delete from student where age = 16
~'
delete from student where age = 20 and name="徐佳莹"
//多条件时用and,or
~
//删除表中所有记录
~使用truncate删除表中数据
truncate student
//只能删除表中所有记录