在執行批處理時將執行錯誤的語句記錄下來並寫到日志文件中去




    public static void executesqls(List<String> sqlList) throws IOException{//改
     Connection con = null;
  Statement sm = null;
  File file = new File("d:\\a.txt");//此處不能寫死,后續要改
       
  FileWriter writer = new FileWriter(file, true);
  
        String outPutFile="";
        String endLine = System.getProperty("line.separator"); // 獲取換行符
  try {
   // 加載驅動
   Class.forName("oracle.jdbc.driver.OracleDriver");
   // 得到連接
     con = DriverManager.getConnection(
     "jdbc:oracle:thin:@192.168.1.0:1521:orcl", "username", "password");
   con.setAutoCommit(false);// 關閉自動提交,提高執行效率
   sm = con.createStatement();

   for (int i = 0; i < sqlList.size(); i++) {
    sm.addBatch(sqlList.get(i));
    if (i % 1000 == 0 || i == (sqlList.size() - 1)) {// 每1000條提交一次,避免內存溢出,應每x條提交一次數據。
     /*sm.executeBatch();
     con.commit();
     sm.clearBatch();*/
    }
   }
   sm.executeBatch();
   con.commit();
   sm.clearBatch();
  } catch (Exception e) {
   if (e instanceof BatchUpdateException) {
    BatchUpdateException bException = (BatchUpdateException) e;
    int[] s = bException.getUpdateCounts();
    outPutFile = "語句: " + sqlList.get(s.length) + " 執行失敗" + endLine;
    writer.write(outPutFile);// 將出錯語句寫入到文件
    writer.flush();
    if (s.length + 1 < sqlList.size()) {
     List<String> sList = sqlList.subList(s.length + 1, sqlList.size());
     executesqls(sList);
    }
   } else {
    e.printStackTrace();
    try {
     if (sm != null)
      sm.close();
    } catch (SQLException ex) {
     ex.printStackTrace();
    }
    try {
     con.close();
    } catch (SQLException ex) {
     ex.printStackTrace();
    }
   }
  } finally {
   try {
    if (sm != null)
     sm.close();
   } catch (SQLException ex) {
    ex.printStackTrace();
   }
   try {
    con.close();
   } catch (SQLException ex) {
    ex.printStackTrace();
   }
   if (writer != null) {
    writer.close();
   }
  }
    }


注意!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。



 
粤ICP备14056181号  © 2014-2021 ITdaan.com