Mysql插入數據的SQL語句主要有:
1、insert into表示插入數據,數據庫會檢查主鍵,如果出現重復會報錯;
2、replace into表示插入替換數據,需求表中有PrimaryKey,或者unique索引,如果數據庫已經存在數據,則用新數據替換,如果沒有數據效果則和insert into一樣;
3、insert ignore表示,如果表中如果已經存在相同的記錄,則忽略當前新數據;
create table testtb(
id int not null primary key,
name varchar(50),
age int
);
insert into testtb(id,name,age)values(1,'bb',13);
select * from testtb;
insert ignore into testtb(id,name,age)values(1,'aa',13);
select * from testtb;
replace into testtb(id,name,age)values(1,"aa",12);
select * from testtb;
4、on duplicate key update 使用該語法可在插入記錄的時候先判斷記錄是否存在,如果不存在則插入,否則更新,很方便,無需執行兩條SQL
注:需要設置Mysql表的unique唯一索引值