JDBC executeBatch 拋出異常中止

進行批量更新的時候發現:sql

addBatch(sql);數據庫

executeBatch 拋出異常後,剩餘的sql沒有更新,即出現異常以前的都入庫了,異常以後即便有可執行sql都不會執行。spa

百度資料後瞭解:這是DBMS數據庫管理系統控制的,有的DBMS在異常以後,剩下的sql也會執行,有的DBMS異常以後其他的不入庫。code

個人改進方法以下:public static boolean bachInsertData(List<String> sqlList) {  boolean bool = false;  Connection conn = null;blog

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;
    }

 

  之前不知道哇啊啊啊啊,好多得改!!!get

相關文章
相關標籤/搜索