java 批处理sql

开发中遇到需要批处理的;特此记录下

 // 数据库配置
        String dbKey = XhjFinalData.db;
        // 数据库ip
        String dbIpKey = XhjFinalData.dbIp;
        // 数据库名称
        String dbNameKey = XhjFinalData.dbName;
        // 数据库登录账号
        String dbNoKey = XhjFinalData.dbNo;
        // 数据库登录密码
        String dbPwdKey = XhjFinalData.dbPwd;
        String dbIp = (String) jsonDataMap.get(dbIpKey);
        String dbName = (String) jsonDataMap.get(dbNameKey);
        String dbNo = (String) jsonDataMap.get(dbNoKey);
        String dbPwd = (String) jsonDataMap.get(dbPwdKey);
        String url = "";
        // 构建一个以ID为键 实体为值的map
        Map<String, XhjWechatChattingRecordsEntity> map = new HashMap<String, XhjWechatChattingRecordsEntity>();
        if (StringUtils.isEmpty(dbIp) || StringUtils.isEmpty(dbName) || StringUtils.isEmpty(dbNo)) {
            return "";
        } else {
            // 批处理
            int a = 1;
            int b = 1;
            int c = 1;
            url = "jdbc:mysql://" + dbIp + ":3306/" + dbName + "?useUnicode=true&characterEncoding=UTF-8";
            Connection conn;
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection(url, dbNo, dbPwd);
            // Connection的自动提交模式关闭,默认是true(自动提交)
            boolean autoCommit = conn.getAutoCommit();
            if (true == autoCommit) {
                conn.setAutoCommit(false);
            }
            Statement stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
        int flag = 0;
                     for(chattingRecordsEntityList (需要循环处理的数据) ){
           String sql = "insert into  tableName"+ " set id = '" + uuid + "',msg_id = '"
                  + chattingRecordsEntity.getMsgId()  + ......
                  stmt.addBatch(sql);
               }
               if (flag == chattingRecordsEntityList.size()) {
                 stmt.executeBatch();
                 stmt.clearBatch();
                 conn.commit();
                 System.out.println(new Date() + "  :  " + "本次新增数据" + flag + "条");
                }
               flag += 1;
            }                             
           conn.close();    
    }
}

 

posted @ 2019-04-14 17:47  闲有余日~~正可学问  阅读(774)  评论(0编辑  收藏  举报