插入,数据库约束,设置列值自动增长
1.插入数据
语法1
#INSERT INTO 表名(列名1,列名2)VALUES(值1,值2);
INSERT INTO person (id,name) VALUES(1,'李四')
语法2:不指定列名
但是要按照数据库表中的顺序,进行书写
INSERT INTO person VALUES(NULL ,'李四')
2.数据库约束
#表的约束:维护数据完整性,给列唯一的标识
#创建表时候设置主键约束
CREATE TABLE student(
id INT PRIMARY KEY,
name VARCHAR(20)
);
#主键是唯一的,不能为空
INSERT INTO student(id,name) VALUES(2,'zhouli')
INSERT INTO student (id,name)VALUES(1,'张三')
#非空约束:添加了非空的列,该列不能为空
NOT NULL
CREATE TABLE studen2(
id INT PRIMARY KEY,
name VARCHAR(20) NOT NULL
);
INSERT INTO student2 (id,name)VALUES(1,'张三')
#唯一约束
CREATE TABLE studen3(
id INT PRIMARY KEY,
name VARCHAR(20),
idcard INT UNIQUE
);
INSERT INTO student3 (id,name,idcard)VALUES(1,'赵六',123);
INSERT INTO student3 (id,name,idcard)VALUES(1,'张三',12);
#外键约束(多表学)
#设置字段自动增长
# auto_increment
CREATE TABLE studen4(
id INT PRIMARY KEY auto_increment,
name VARCHAR(20)
)auto_increment = 100;
#auto_increment = 100; 给的起始值
INSERT INTO student4(id,name) VALUES(2,NULL);
3.简单查询,删除,插入语句
#准备测试数据
CREATE TABLE student(
id INT,
name VARCHAR (20),
age INT,
code INT,
score INT
);
INSERT INTO student VALUES(1,'李四',25,001,59);
INSERT INTO student VALUES(2,'王五',25,002,60);
INSERT INTO student VALUES(3,'六',25,003,70);
INSERT INTO student VALUES(4,'七',25,004,80);
INSERT INTO student VALUES(5,'八',25,005,60);
INSERT INTO student VALUES(6,'九',25,006,70);
INSERT INTO student VALUES(7,'十',25,007,80);
#查询所有数据
SELECT *FROM student;
#查询指定的列
SELECT id FROM student;
#更新
#更新某个表中id字段值为1的记录吧,将记录中的name 字段值改为“哈哈”
/*UPDATE 表名
SET
列名 1 = 值1,
列名 2 = 值2,
WHERE列名 = 条件值
*/
UPDATE student SET name = '哈哈' WHERE id = 1;
# 更新某个表中的id小于3的记录,将 age 字段值都更新为100
UPDATE student SET age = 100 WHERE id < 3;
#更新表中所有的记录,将name 字段都改为“无名”
UPDATE student set name="无名";
#删除
#DELETE FROM 表名 WHERE 条件
DELETE FROM student WHERE id = 1;
#删除全部数据 方式一,延续使用之前自动增长
DELETE FROM student;
#方式二
TRUNCATE TABLE student;