Java JDBC批處理插入數據操作

原文:http://www.cnblogs.com/kahreman/archive/2012/08/06/2625827.html
方法一:

String[] queries = { 
        "insert into employee (name, city, phone) values ('A', 'X', '123')",
        "insert into employee (name, city, phone) values ('B', 'Y', '234')",
        "insert into employee (name, city, phone) values ('C', 'Z', '345')"};
Connection connection = new getConnection();
Statement statemenet = connection.createStatement();
 for (String query : queries) {
    statemenet.addBatch(query);
}
statemenet.executeBatch();
statemenet.close();
connection.close();

使用addBatch方法添加SQL,使用executeBatch一次性執行批量插入操作。

方法二:
當插入的數據是動態的,需要用PreparedStatement對象實現功能。

String sql = "insert into employee (name, city, phone) values (?, ?, ?)";
Connection connection = new getConnection();
PreparedStatement ps = connection.prepareStatement(sql);
 for (Employee employee: employees) {
    ps.setString(1, employee.getName());
    ps.setString(2, employee.getCity());
    ps.setString(3, employee.getPhone());
    ps.addBatch();
}
ps.executeBatch();
ps.close();
connection.close();

操作類似Statement,只是增加了設置插入值的功能。

方法三:
上面的解決方案仍然存在一個問題。考慮這樣一個場景,在您想要插入到數據庫使用批處理上萬條記錄。嗯,可能產生的OutOfMemoryError:

java.lang.OutOfMemoryError: Java heap space
com.mysql.jdbc.ServerPreparedStatement$BatchedBindValues.<init>(ServerPreparedStatement.java:72)
com.mysql.jdbc.ServerPreparedStatement.addBatch(ServerPreparedStatement.java:330)
org.apache.commons.dbcp.DelegatingPreparedStatement.addBatch(DelegatingPreparedStatement.java:171)

分批次執行批量插入操作

String sql = "insert into employee (name, city, phone) values (?, ?, ?)";
Connection connection = new getConnection();
PreparedStatement ps = connection.prepareStatement(sql);
final int batchSize = 1000;
int count = 0;
for (Employee employee: employees) {
    ps.setString(1, employee.getName());
    ps.setString(2, employee.getCity());
    ps.setString(3, employee.getPhone());
    ps.addBatch();
    if(++count % batchSize == 0) {
        ps.executeBatch();
    }
}
ps.executeBatch(); // insert remaining records
ps.close();
connection.close();

考慮批量大小爲1000,每1000個查詢語句爲一批插入提交。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章