隨筆緣由:
系統完成到一定程度,少不了要往數據庫中添加大量數據進行性能測試。 我用程序做數據10W條,使用jdbc批更新的API,發現每次只能插入2W多條記錄。 一番小小研究,覺得總結一下可能有些意義。
總結內容如下:
1:這是我出現問題的代碼,插入10W條數據,10W次數據進行一次批處理,發現只能插入24464多條數據,程序也沒有報錯。
Connection con = (Connection) DriverManager.getConnection(url,user,password);
con.setAutoCommit(false);
Long startTime = System.currentTimeMillis();
PreparedStatement pst = (PreparedStatement) con.prepareStatement(sql.toString());
for (int i = 0; i < list.size(); i++) {
KIVResponseBean kivResponseBean=list.get(i);
pst.setString(1, kivResponseBean.getK());
pst.setString(2, kivResponseBean.getI());
pst.setInt(3, kivResponseBean.getV());
pst.setInt(4, kivResponseBean.getD());
pst.setString(5, kivResponseBean.getM());
pst.setString(6, kivResponseBean.getR());
pst.addBatch();
}
pst.executeBatch();
con.commit();
Long endTime = System.currentTimeMillis();
System.out.println("用時:" + (endTime - startTime));
2:在不使用批更新時,具體做法就是 不添加這句代碼 con.setAutoCommit(false); 並且每次為SQL指定參數后就執行 pst.executeUpdate(); 提交數據;結果10W條記錄插入成功,但是使用了 35833ms的時間消耗。
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = (Connection) DriverManager.getConnection(url,user,password);
Long startTime = System.currentTimeMillis();
PreparedStatement pst = (PreparedStatement) con.prepareStatement(sql.toString());
for (int i = 0; i < list.size(); i++) {
KIVResponseBean kivResponseBean=list.get(i);
pst.setString(1, kivResponseBean.getK());
pst.setString(2, kivResponseBean.getI());
pst.setInt(3, kivResponseBean.getV());
pst.setInt(4, kivResponseBean.getD());
pst.setString(5, kivResponseBean.getM());
pst.setString(6, kivResponseBean.getR());
pst.executeUpdate();
}
Long endTime = System.currentTimeMillis();
System.out.println("用時:" + (endTime - startTime));
3:使用批更新,並且制定沒10000次提交一次更新,此時 使用時間 2980 ms ,10w條數據也批量添加成功,oracle對每次執行的批更新有限制,我在11g的環境下測試 在2W4K多,網上有朋友說在10g下 每次提交1W多數據就會報錯。
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = (Connection) DriverManager.getConnection(url,user,password);
con.setAutoCommit(false);
Long startTime = System.currentTimeMillis();
PreparedStatement pst = (PreparedStatement) con.prepareStatement(sql.toString());
int batchCount=list.size()/batchSize+1;
for(int batch=0;batch<batchCount;batch++) {
for (int i = batch*batchSize; (i <(batch+1)*batchSize)&&(i<list.size()); i++) {
KIVResponseBean kivResponseBean=list.get(i);
pst.setString(1, kivResponseBean.getK());
pst.setString(2, kivResponseBean.getI());
pst.setInt(3, kivResponseBean.getV());
pst.setInt(4, kivResponseBean.getD());
pst.setString(5, kivResponseBean.getM());
pst.setString(6, kivResponseBean.getR());
pst.addBatch();
}
pst.executeBatch();
con.commit();
pst.clearBatch();
}
Long endTime = System.currentTimeMillis();
System.out.println("用時:" + (endTime - startTime));
