添加数据
通常情况下,向数据表中添加的新记录应该包含表的所有字段,即为该表中的所有字段添加数据,为表中所有字段添加数据的INSERT语句有两种:
1.NSERT语句中指定字段名
INSERT INTO 表名(字段名) VALUES(值);
INSERT INTO 表名(字段名1,字段名2,……) VALUES(值1,值2,……);
注意:必须列出表所有字段的名称,每个值的顺序、类型必须与对应的字段相匹配。
2.INSERT语句中不指定字段名
INSERT INTO 表名 VALUES(值1,值2,……)
注意:由于INSERT语句中没有指定字段名,添加的值的顺序必须和字段在表中定义的顺序相同。
MySQL中,也可以在INSERT语句中只向部分字段中添加值。
3.INSERT语句中只向部分字段中添加值
INSERT INTO 表名 SET 字段名1=值1[,字段名2=值2,……]
注意:如果在SET关键字后面指定了多个"字段名=值"对,每对之间使用逗号分隔,最后一个"字段名=值"对之后不需要逗号。
有时,也需要一次向表中添加多条记录,所以在MySQL中,也提供了如何使用一条INSERT语句同时添加多条记录的功能。
4.一条INSERT语句同时添加多条记录
INSERT INTO 表名[(字段名1,字段名2,……) ]
VALUES(值1,值2,……),(值1,值2,……),
… …
(值1,值2,……);
示例
#为字段name添加数据
mysql> insert into classes(name) values('1班');
Query OK, 1 row affected (0.13 sec)
#同时添加多条记录
mysql> insert into classes(name) values('2班'),('3班'),('4班');
Query OK, 3 rows affected (0.10 sec)
Records: 3 Duplicates: 0 Warnings: 0
#添加一条数据到student表中
#因为主键是自增长的,不需要我们手动设置
insert into students(name,age,gender,height,enrollment_time,allowance,cid)
values('小明',18,'男',170,'1990-02-02',50,null);
#新增记录时,可以指定要设置的列,但是需要考虑非空列也必须设置值
insert into students(name,age,gender)
values('小汪',18,'男');
#为student表添加多条数据
insert into students(name,age,gender,height,enrollment_time,allowance,cid) values('张三',18,'男',180,'1980-12-17',30,1);
insert into students(name,age,gender,height,enrollment_time,allowance,cid) values('李四',20,'女',150,'1981-02-20',50,2);
insert into students(name,age,gender,height,enrollment_time,allowance,cid) values('王五',38,'男',170,'1985-02-22',60,3);
insert into students(name,age,gender,height,enrollment_time,allowance,cid) values('赵六',28,'女',155,'1983-04-02',50,1);
insert into students(name,age,gender,height,enrollment_time,allowance,cid) values('孙七',29,'男',168,'1981-09-28',50,2);
insert into students(name,age,gender,height,enrollment_time,allowance,cid) values('张雷',30,'男',171,'1984-05-01',50,3);
#为student表批量插入数据(同时添加多条数据)
insert into students(name,age,gender,height,enrollment_time,allowance,cid)
values
('小王',18,'男',170,'1990-02-02',50,null)
,('小张',18,'男',170,'1990-02-02',50,null)
,('小李',18,'男',170,'1990-02-02',50,null)
,('小六',18,'男',170,'1990-02-02',50,null);
