进行批量更新的时候发现:
addBatch(sql);
executeBatch 抛出异常后,剩余的sql没有更新,即出现异常之前的都入库了,异常之后即使有可执行sql都不会执行。
百度资料后了解:这是DBMS数据库管理系统控制的,有的DBMS在异常之后,剩下的sql也会执行,有的DBMS异常之后其余的不入库。
我的改进方法如下:public static boolean bachInsertData(List<String> sqlList) { boolean bool = false; Connection conn = null;
public static boolean bachInsertData(List<String> sqlList) { boolean bool = false; Connection conn = null; Statement stm = null; try { conn = MyDAO.getConnection(); conn.setAutoCommit(false); stm = conn.createStatement(); for (String sql : sqlList) { stm.addBatch(sql); } stm.executeBatch(); conn.commit(); bool = true; } catch (Exception e) { if(e instanceof BatchUpdateException){ BatchUpdateException bException = (BatchUpdateException)e; int[] s = bException.getUpdateCounts(); logger.info("更新失败数据:"+sqlList.get(s.length)); if(s.length+1<sqlList.size()){ List<String> sList = sqlList.subList(s.length+1, sqlList.size()); bachInsertData(sList); } }else{ e.printStackTrace(); try { if (stm != null) stm.close(); } catch (SQLException ex) { ex.printStackTrace(); } try { conn.close(); } catch (SQLException ex) { ex.printStackTrace(); } } } finally { try { if (stm != null) stm.close(); } catch (SQLException ex) { ex.printStackTrace(); } try { conn.close(); } catch (SQLException ex) { ex.printStackTrace(); } } return bool; }
以前不知道哇啊啊啊啊,好多得改!!!