今天用jdbc批量添加数据的时候遇到了一个问题,当数据添加成功过后,再想对该表进行操作发现表被锁住了,检查了下代码发现事务提交了呀!!!!!!!!!!!!
去网上查了大半天的资料才发现问题,在connection commit过后需要加上 connection.setAutoCommit(true);
下面是示例代码
log.info("插入语句" + sql); //获取结果集 connection = JdbcUtils.getConnection(database.getMysqlDriverName(), database.getMysqlUrl(), database.getMysqlUserName(), database.getMysqlPassWord()); if (connection != null) { //设置为false,事务不会自动提交 connection.setAutoCommit(false); try { ps = connection.prepareStatement(sql); } catch (Exception e) { log.error("--------------------sql语句错误----------------------------"); } try { for (int i = 0; i < tsImAnalysisList.size(); i++) { ps.setString(1, tsImAnalysisList.get(i).getSessionNum()); ps.setObject(2, tsImAnalysisList.get(i).getCreateTime()); ps.setString(3, tsImAnalysisList.get(i).getType()); ps.setString(4, tsImAnalysisList.get(i).getSponsorDept()); ps.setString(5, tsImAnalysisList.get(i).getFirstLevelDept()); ps.setString(6, tsImAnalysisList.get(i).getTwoLevelDept()); ps.setString(7, tsImAnalysisList.get(i).getThreeLevelDept()); ps.setString(8, tsImAnalysisList.get(i).getSponsorName()); ps.setLong(9, tsImAnalysisList.get(i).getSponsorUserId()); ps.setLong(10, tsImAnalysisList.get(i).getReplyUserId()); ps.setString(11, tsImAnalysisList.get(i).getReplyUserName()); ps.setLong(12, tsImAnalysisList.get(i).getFirstResponseTime()); ps.setLong(13, tsImAnalysisList.get(i).getTotalDuration()); ps.setObject(14, LocalDateTime.now()); ps.addBatch(); } //执行批处理 ps.executeBatch(); //提交 connection.commit(); connection.setAutoCommit(true); ps.clearBatch(); if (ps.executeUpdate() > 0) { return 1; } } catch (Exception e) { //回滚事务 // connection.rollback(); log.error("集合数据赋值异常" + e); } //关闭连接 //关闭连接 JdbcUtils.colseResource(connection, ps, rs);
原文地址:https://www.cnblogs.com/fzyang/p/10803627.html
时间: 2024-10-09 16:21:39