对测试的表添加unique唯一约束。

alter table test.wc_res add unique

(word);​

1、insert IGNORE into test.wc_res(word,count)

values(#{word},#{count})

使用ignore into时,如果数据存在,不抛出错误,存在的数据不插入

2、insert  into test.wc_res(word,count)

values(#{word},#{count})

Caused by:

com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException:

Duplicate entry 'zhangfei' for key 'word'

​​​

a4c26d1e5885305701be709a3d33442f.png

3、​insert REPLACE

into test.wc_res(word,count) values(#{word},#{count})

1064 - You have an error in your SQL syntax; check the

manual that corresponds to your MySQL server version for the right

syntax to use near 'REPLACE  into

test.wc_res(word,count) values("zhangfei",2)' at line

1​

replace into时产生原因:语法错误。正确的语法应该是没有insert:

​REPLACE  into

test.wc_res(word,count) values(#{word},#{count})

如果存在primary or

unique相同的记录,则先删除掉。再插入新记录。​

4、insert … select … where not exist

根据select的条件判断是否插入,可以不光通过primary 和unique来判断,也可通过其它条件。例如:

INSERT INTO books (name) SELECT 'MySQL Manual' FROM dual WHERE

NOT EXISTS (SELECT id FROM books WHERE id = 1)

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐