我想執行下列確切SQL查詢:如何獲取包含在批處理例外
(從處理數據庫的讀取行轉移到PRESENTATION DB一排)
PreparedStatement stmt;
Statement st;
Connection conn = ConnectionManager.getInstance().getConnection(ConnectionManager.PRESENTATION_DB);
try {
conn.setAutoCommit(false);
stmt = conn.prepareStatement(
"insert into customer (name,category,age) values (?,?,?)");
stmt.clearParameters();
stmt.setString(1,"name2");
stmt.setString(2,"cat2");
stmt.setInt(3,25);
stmt.addBatch();
stmt.clearParameters();
stmt.setString(1,"name3");
stmt.setString(2,"cat3");
stmt.setInt(3,25);
stmt.addBatch();
stmt.clearParameters();
stmt.setString(1,"name4");
stmt.setString(2,"cat2");
stmt.setInt(3,25);
stmt.addBatch();
stmt.clearParameters();
stmt.setString(1,"name4");
stmt.setString(2,"cat2");
//stmt.setInt(3,25);
//this is parameter with false input
stmt.setString(3,"null");
stmt.addBatch();
stmt.clearParameters();
stmt.setString(1,"name5");
stmt.setString(2,"cat5");
stmt.setInt(3,25);
stmt.addBatch();
stmt.clearParameters();
int [] updateCounts = stmt.executeBatch();
conn.commit();
conn.setAutoCommit(true);
stmt.close();
conn.close();
}
catch(BatchUpdateException b) {
System.err.println("-----BatchUpdateException-----");
System.err.println("SQLState: " + b.getSQLState());
System.err.println("Message: " + b.getMessage());
System.err.println("Vendor: " + b.getErrorCode());
System.err.print("Update counts: ");
int [] updateCounts = b.getUpdateCounts();
for (int i = 0; i < updateCounts.length; i++) {
System.err.print(updateCounts[i] + " ");
}
System.err.println("");
}
catch (Exception e) {
e.printStackTrace();
}
如何識別導致異常能夠在沒有這個特定行的情況下重新執行批處理的行? (通過更新行的字段hasError)。
目前我不是通過批量保存對象,因此如果它導致錯誤並跳過該行並繼續處理(即保存/傳輸和刪除)另一行,則可以標記該行。
謝謝!
更新:
好的,我用下面的代碼來跟蹤行(如果有的話行導致錯誤):
public static void processUpdateCounts(int[] updateCounts) {
for (int i=0; i<updateCounts.length; i++) {
if (updateCounts[i] >= 0) {
// Successfully executed; the number represents number of affected rows
logger.info("Successfully executed: number of affected rows: "+updateCounts[i]);
} else if (updateCounts[i] == Statement.SUCCESS_NO_INFO) {
// Successfully executed; number of affected rows not available
logger.info("Successfully executed: number of affected rows not available: "+updateCounts[i]);
} else if (updateCounts[i] == Statement.EXECUTE_FAILED) {
logger.info("Failed to execute: "+updateCounts[i]);
// Failed to execute
}
}
}
而且增加了行:
processUpdateCounts(updateCounts);
所以我可以看到有或沒有任何錯誤的變化,但它看起來像BatchUpdateException不起作用?從的BatchUpdateException的的Javadoc
嗨,感謝您的即時回覆,我已更新我的問題,並希望能爲此輸入任何信息,謝謝! – eunique0216 2011-03-08 05:50:24