mysql 批量插入数据如何防止重复插入

  • Post author:
  • Post category:mysql


mysql批量插入数据时,会存在重复数据的可能.

解决方法:


1)数据库加联合索引

2)修改sql,忽略重复的数据,防止数据库报错



1.


CREATE TABLE `merchantBlackList` (
  `id` int(5) NOT NULL AUTO_INCREMENT,
  `createTime` datetime NOT NULL,
  `bankId` int(10) DEFAULT NULL COMMENT '银行id',
  `merchantSn` varchar(20) COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '商户编号',
  PRIMARY KEY (`id`),
  UNIQUE KEY `bankId_merchantSn` (`bankId`,`merchantSn`)//联合索引
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;


2.

<insert id="batchInsert"  parameterType="ArrayList">
        INSERT INTO merchantBlackList(createTime,bankId,merchantSn)
        VALUES
        <foreach collection="list" item="item" index="index" separator="," >
            (#{item.createTime},#{item.bankId},#{item.merchantSn})
        </foreach>
        ON DUPLICATE KEY UPDATE
        bankId=VALUES(bankId),
        merchantSn=VALUES(merchantSn);
    </insert>



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