常見插入數(shù)據(jù)的SQL
insert into 插入數(shù)據(jù)庫時會檢查主鍵是否存在,存在會報錯
replace into 替換數(shù)據(jù)庫記錄假勿,需要表中有主鍵或者unique索引,如果數(shù)據(jù)庫已存在的數(shù)據(jù)态鳖,會先刪除該數(shù)據(jù)然后新增转培。不存在的數(shù)據(jù)效果和insert into 一樣。
<insert id="insertInfoBatch" parameterType="java.util.List">
replace into GOVRECEIPTS (state,orgname,orgaddr,regauth,rcptyear,receipts,crtdate)
values
<foreach collection="list" item="item" index="index" separator=",">
(#{item.state}, #{item.orgname}, #{item.orgaddr}, #{item.regauth},
#{item.rcptyear}, #{item.receipts}, #{item.crtdate})
</foreach>
</insert>
insert ignore 需要表中有主鍵或者unique索引浆竭,如果數(shù)據(jù)庫中存在相同的數(shù)據(jù)浸须,則忽略當(dāng)前數(shù)據(jù)。不存在的數(shù)據(jù)效果和insert into 一樣邦泄。
<insert id="insertInfoBatch" parameterType="java.util.List">
insert ignore GOVRECEIPTS (state,orgname,orgaddr,regauth,rcptyear,receipts,crtdate)
values
<foreach collection="list" item="item" index="index" separator=",">
(#{item.state}, #{item.orgname}, #{item.orgaddr}, #{item.regauth},
#{item.rcptyear}, #{item.receipts}, #{item.crtdate})
</foreach>
on duplicate key update 使用該語法可在插入記錄的時候先判斷記錄是否存在删窒,如果不存在則插入,否則更新顺囊,很方便易稠,無需執(zhí)行兩條SQL
注意:需要設(shè)置Mysql表的unique唯一索引值
原文:https://blog.csdn.net/w309827333/article/details/79482407