您的位置:首页 > 其它

在执行批处理时将执行错误的语句记录下来并写到日志文件中去

2015-09-30 15:17 417 查看

    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();

   }

  }

    }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: