[英]Java JDBC - prepared statement for bulk insertion using merge sort
我正在使用JDBC准備的語句進行批量插入。 我正在調用ps.execute()
方法。 如果失敗,那么我正在調用一種方法,其中我要傳遞參數列表和准備好的語句。 我正在使用merge sort technique to divide the list
,然后嘗試插入記錄,但沒有成功。
這是我的代碼;
從我正在調用的executePrepareStatement方法
this.executeInsertStatement(query, myCollection, 0, myCollection.size());
// executeInsertStatement方法
public void executeInsertStatement1(String query, List myCollection, int sIndx, int eIndx) throws DBException,SQLException {
int startIndx = sIndx, endIndx = eIndx, mid = 0;
try {
try{
if(conn.isClosed())
new DataService(CoreConstants.TARGET);
} catch (Exception e) { }
if(startIndx >= endIndx) {
return;
}
conn.setAutoCommit(false);
if (query != null) {
mid = (startIndx + endIndx) / 2;
ps = conn.prepareStatement(query);
executeInsertStatement(query, myCollection, startIndx, mid);
executeInsertStatement(query, myCollection, mid+1, endIndx);
//int end_low = mid;
//int start_high = mid + 1;
if(mid < endIndx)
endIndx = mid;
for (int i = 0; i < endIndx; i++) {
List list = (List) myCollection.get(i);
int count = 1;
for (int j = 0; j < list.size(); j++) {
if(list.get(j) instanceof Timestamp) {
ps.setTimestamp(count, (Timestamp) list.get(j));
} else if(list.get(j) instanceof java.lang.Character) {
ps.setString(count, String.valueOf(list.get(j)));
}
else {
ps.setObject(count, list.get(j));
}
count++;
}
try {
ps.execute();
} catch (Exception e) {
rollback();
}
}
}
} catch (Exception e) {
rollback();
} finally{
try {
if (ps != null) {
ps.close();
ps = null;
}
} catch (Exception ex) {
}
}
}
謝謝
我認為您使用合並排序的方式並不正確。 我了解您正在嘗試使用分而治之的概念來實現您的解決方案,但是我認為您使問題變得比真正需要的更加困難( 並且更加令人困惑/復雜 )。
如果我理解正確,則您有一個要插入數據庫的數據集。 您可能要批量進行。 PreparedStatement讓我們通過使用幾個簡單的方法來做到這一點: addBatch()
和executeBatch()
這是我將如何嘗試實現您的要求的概述:
我要設置批次限制,即當我想執行該批次時,我的批次中的語句數。 除非達到此限制( 可以使用計數器很好地跟蹤它 ),否則我將繼續添加到批次中
達到限制后,我將執行批處理,重置計數器,清除批處理並重新執行步驟1
這將一直持續到我完成整個數據集為止。 最后,根據我的要求,我要么將數據提交到數據庫,要么執行回滾。
請看一下此答案 ,以獲取有關如何執行和實施此示例的示例。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.