
正文
insert增数据详解
提示:扫一扫查出行【扫一扫了解最新限行尾号】
复制提示
查看表结构:desc 表名;
desc 表名;
describe的缩写,意为描述

增加数据不会改变表的结构,只是增加了行。
创建一张表: mysql> create table class(
-> id int primary key auto_increment,
-> name varchar(10) not null default '',
-> gender char(1) not null default '',
-> company varchar(20) not null default '',
-> salary decimal(6,2) not null default 0.00,
-> fanbu smallint not null default 0
-> );
- 把id设置为主键、自增(自增的主键在添加数据可以不写)
- name、gender、company、salary、fanbu这些属性都设置为不能为空,如果没有添加则默认为空字符串、0.0
- decimal(6,2),表示薪资有六位数,小数点后占两位
mysql> create table class(
-> id int primary key auto_increment,
-> name varchar(10) not null default '',
-> gender char(1) not null default '',
-> company varchar(20) not null default '',
-> salary decimal(6,2) not null default 0.00,
-> fanbu smallint not null default 0
-> );
insert步骤:
- 往哪张表添加行?
- 给哪几列添加值?
- 分别是什么值?
mysql> insert into class
-> (id,name,gender,company,salary,fanbu)
-> values
-> (1,'张三','男','百度',8888.66,145);

在添加数据之前,如果使用gbk编码,可能导致中文字符的长度不够的错误,所以可以使用:
mysql> set names utf8mb4;
再次添加数据:mysql> insert into class
-> (name,gender,salary)
-> values
-> ('李四','男',9832.23);
mysql> insert into class
-> (name,gender,salary)
-> values
-> ('李四','男',9832.23);
这次没有全部添加

虽然没有添加id,但还是显示2,因为前面设置了id为自增的,每次添加数据id都会加一,没有添加的使用默认设置的值。
如果插入所有列,则可以不声明待插入的列,默认为依次插入所有列
此时id也必须添加或写null占位(不推荐,会出现兼容问题),否则不会对应
mysql> insert into class
-> values
-> (3,'王五','女','腾讯',3245.23,435);

如果想添加多行,则每行记录间用逗号隔开
insert into class (name,company,salary) values ('刘备','皇家',23.34), ('曹操','宦官后裔',34.34);







