插入MySQL数据库前去除重复数据的几种方法

11 篇文章 0 订阅

在数据存储过程中,可能会遇到数据主键重复的情况,我们可以通过下面几个方法进行处理:
1. 若数据不存在插入,存在更新
2. 使用duplicate key关键字,如插入数据时发生主键冲突就更新数据
3. 使用Ingore关键字
4. 使用replace into关键字

一、若数据不存在插入,存在更新:

    private void saveBrand(List<BrandEntity> brandList) {
           String sql = null;
           Connection con = null;
           PreparedStatement ps = null;
           ResultSet rs = null;
            try {
                 con = getParallelImportCarConnection();
                 for (BrandEntity br : brandList) {
                     String brandName = br. name;
                      sql = "select name from parallel_import_car.mt_brand where name = ?";
                      ps = con.prepareStatement( sql);
                      ps.setString(1, brandName);
                      rs = ps.executeQuery();
                      if ( rs.next()) {
                            sql = "update parallel_import_car.mt_brand set update_time = NOW()";
                            ps = con .prepareStatement( sql);
                            ps.executeUpdate();
                     } else {
                            sql = "INSERT INTO mt_brand(id,name,initial,url,update_time) "
                                     + "VALUES (?,?,?,?,NOW())";
                            ps = con .prepareStatement( sql);
                            int index = 1;
                            ps.setInt( index++, DBUtilForOkeycar.nextSeq( con, "brand_id"));
                            ps.setString( index++, brandName);
                            ps.setString( index++, br. initial);
                            ps.setString( index++, br. url);
                            ps.executeUpdate();
                     }
                }
           } catch (SQLException e) {
                 e.printStackTrace();
           } finally {
                Toolkit. close( con, rs, ps);
           }
     }

二、使用duplicate key关键字,如插入数据时发生主键冲突就更新数据
如果数据表存在主键或者索引,可以使用 on duplicate key 来实现重复数据更新

    private static void insert(String modelId, String modelDetail) {
        Connection con = getCVCHomeConnection();
        PreparedStatement ps = null;
        String sql = "";
        try {
            sql = "insert into mt_detail(model_id,detail,source,update_time) values(?,?,?,now()) on duplicate key update detail=?, update_time=now()";
            ps = con.prepareStatement(sql);
            ps.setString(1, modelId);
            ps.setString(2, modelDetail);
            ps.setString(3, "cvchome");
            ps.setString(4, modelDetail);
            ps.executeUpdate();

        } catch(Exception e) {
            logger.error("insertModelDetail error!",e);
        } finally {
            Toolkit.close(con, null, ps);
        }

    }

三、使用Ingore关键字:
如果是用主键primary或者唯一索引unique区分了记录的唯一性,避免重复插入记录可以使用ingore关键字。
格式如:INSERT IGNORE INTO * 或者 UPDATE IGNORE SET *
eg: insert ingore into test(?,?) values(1,”test”);

四、使用replace into关键字:
replace into 是insert into的增强版。在向表中插入数据时,首先判断数据是否存在;如果不存在,则插入;如果存在,则更新。即旧记录与新记录有相同的值,则在新记录被插入之前,旧记录被删除。
逻辑类似于:if not exists (select 1 from t where id = 1) ?
insert into t(id, update_time) values(1, getdate())
else
update t set update_time = getdate() where id = 1

MySQL replace into 有三种形式:
1、 replace into table(col_name, …) values(…)
用法类似于insert into的方法
2、 replace into table(col_name, …) select …
eg:replace into tb1( name, title,) select name, rtitle from tb2;
3、 replace into table name=value, …
用法类似于update set用法,使用一个例如“SET name = name + 1”的赋值,则对位于右侧的列名称的引用会被作为DEFAULT(name)处理。因此,该赋值相当于SET name = DEFAULT(name) + 1。

  • 2
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值