JDBC批处理补充
最近公司在用DB2数据库,用的DbVisualizer作为数据库管理工具。因为开发库和实际库是分开的,所以经常要从实际库中导出数据到开发库,一般是导出为文件的形式。在数据量小的时候是每没什么问题的,可是当数据量达到10w以上时,DbVisualizer老内存溢出。一气之下,想到了用JDBC的批处理,来实现数据的导入,说干就干,但是在开发的过程中还是遇到很多问题的,大家都知道,JDBC中的Statement和PreparedStatement都是可是做批处理的,但是在我的这个问题中,只能用Statement,因为是每次从文件中读取要导入的sql语句(都是insert语句),每次读入的时候语句都是变的。所以没法用PreparedStatement(预编译SQL)。
第一次写博,不知道各位大牛们,有没有好的方法?
Connection con = null; Statement ps = null; try { FileReader fr = new FileReader("d:/datas.sql"); BufferedReader bis = new BufferedReader(fr); String insertSql; int i = 0; con = getConnection(); ps = con.createStatement(); long start=System.currentTimeMillis(); while ((insertSql= bis.readLine()) != null&& i<3112) { ps.addBatch(insertSql); i++; if (i % 1000 == 0) { ps.executeBatch(); ps.clearBatch(); long now=System.currentTimeMillis(); System.out.println("已完成:" + i+",时间:"+(now-start)+"ms"); } } //执行剩余的sql ps.executeBatch(); } catch (Exception e) { e.printStackTrace(); } finally { try { if (ps != null) ps.close(); if (con != null) con.close(); } catch (Exception e) { e.printStackTrace(); } }
页:
[1]