如何避免MySql数据库的重复插入数据

通常我们需要避免数据库重复插入操作的时候会给表设置主键或唯一索引,当插入重复数据的时候抛出异常,程序终止,但是这样也会存在一定的麻烦,所以就需要我们能尽量的避开或忽略异常。为了演示,我们新建一个User测试表,包括字段id、username、sex、addr四个字段,其中主键为id(自增),同时对username字段设置唯一索引。

一:insert ignore into

即插入数据时,如果数据存在,则忽略此次插入,前提条件是插入的数据字段设置了主键或唯一索引

insert ignore into user(username,sex,addr) values('LISI','man','dongbei');

二:on duplicate key update

即插入数据时,如果数据存在,则执行更新操作,前提条件是插入的数据字段设置了主键或唯一索引

insert into user(username,sex,addr) values('LISI','man','dongbei')
on duplicate key update sex = 'man',addr='dongbei';

三:replace into

即插入数据时,如果数据存在则删除在插入,前提条件是插入的数据字段设置了主键或唯一索引

replace into user(username,sex,addr) values('LISI','man','dongbei')

四:insert if not exists

即insert into …select…where not exist…;这种方式适合没有设置主键或唯一索引的数据,当插入一条记录时首先判断是否存在这样一条记录,不存在插入,存在忽略操作

insert into user(username,sex,addr) 
	select 'LISI','man','dongbei' from user
	where not exists 
	(select username from user where username = 'LISI')

版权声明:本文为fuu123f原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。