向mysql中插入数据
插入数据大致分为三类情况,直接插入、数据已经存在的两种处理情况。它们分别是: insert into、replace into、insert ignore1、insert into
插入数据,数据库会检查主键,如果出现重复会报错。
2、replace into
插入替换数据,需求表中有primary key,或者unique索引;如果数据库已经存在数据,则用新数据替换,如果没有数据效果则和insert into一样。
3、insert ignore
如果表中已经存在相同的记录,则忽略当前数据。
为了直观地说明,我们举例如下:
create table freeoa(
id int not null primary key,
name varchar(50),
age tinyint
);
#插入一条初始记录
insert into freeoa(id,name,age) values(1,"bb",13);
#insert ignore 用法
insert ignore into freeoa(id,name,age)values(1,"aa",13);
select * from freeoa;
#仍是1,"bb",13,因为id是主键,出现主键重复但使用了ignore则该错误将会被忽略
#replace 用法
replace into freeoa(id,name,age)values(1,"aa",12);
select * from freeoa;
#数据变为1,"aa",12,将强制修改。
关于replace的具体用法,可以参考这里。