簡體   English   中英

部分失敗時的executeBatch行為

[英]executeBatch behaviour in case of partial failure

我有一個 java 1.6 應用程序,它使用批處理插入使用 jdbc 驅動程序在 Oracle db 中插入記錄。 如您所知,Statement 對象有一個名為 executeBatch() 的方法,我們使用它進行批量更新。 它有一個 int 數組的返回類型,其中包含每個記錄的執行結果。 但它也會在出錯的情況下拋出 BatchUpdateException ,我們也可以從中獲取結果 int 數組。 我的問題是在什么錯誤情況下我應該期望 BatchUpdateException 以及什么時候我應該期望沒有拋出異常但對於某些記錄我會失敗。

注意:問題特別針對 Oracle JDBC。 為了更清楚地說明,我已經看到在執行 executeBatch() 之后我沒有得到 BatchUpdateException 但是一些插入語句失敗的情況。 我的問題是在什么情況下會發生?

這是 Statement.executeBatch() 方法的返回 javadoc。 根據這里的一般意見,當一個條目失敗時,執行會拋出 BatchUpdateException 然后在這種情況下我們可以預期返回數組中的某些條目失敗。

      * @return an array of update counts, with one entry for each command in the
 *         batch. The elements are ordered according to the order in which
 *         the commands were added to the batch.
 *         <p>
 *         <ol>
 *         <li> If the value of an element is >=0, the corresponding command
 *         completed successfully and the value is the update count for that
 *         command, which is the number of rows in the database affected by
 *         the command.</li>
 *         <li> If the value is SUCCESS_NO_INFO, the command completed
 *         successfully but the number of rows affected is unknown.
 *         <li>
 *         <li> If the value is EXECUTE_FAILED, the command failed.
 *         </ol>
 * @throws SQLException
 *             if an error occurs accessing the database
 */
public int[] executeBatch() throws SQLException;

假設您有 5 個批量更新語句。 他們每個人的執行都是更新20條記錄,事先知道。

一批更新語句的執行發生時沒有BatchUpdateExceptionSQLException被拋出。

如果返回的 int 數組中的任何元素不是 20,那么您就知道出現了意外行為。 這可以被視為失敗。

編輯

來自 BatchUpdateExcpetion 的JavaDoc (亮點是我的補充)

在批量更新中的命令無法正確執行並拋出 BatchUpdateException 后,驅動程序可能會也可能不會繼續處理批處理中的剩余命令。 如果驅動程序在失敗后繼續處理,則 BatchUpdateException.getUpdateCounts 方法返回的數組將包含批處理中每個命令的元素,而不僅僅是錯誤前成功執行的命令的元素。 在驅動程序停止[ed]處理命令的情況下,任何失敗命令的數組元素是 Statement.EXECUTE_FAILED。

我的理解是,如果批處理中的任何語句失敗,則將拋出BatchUpadteException

如果在批處理中間發生錯誤,Oracle JDBC 驅動程序將拋出 BatchUpdateException。

例如,假設您要發送一個包含 10 個條目的批次(在您的案例中插入 10 行)。 條目#0 到#4 是成功的。 條目 #5 遇到錯誤,例如主鍵違規。 執行在 5 處停止,驅動程序拋出 BatchUpdateException。 如果您調用 getUpdateCounts(),您將獲得一個大小為 10 的數組,其中包含 5 個 SUCCESS_NO_INFO 和 5 個 EXECUTE_FAILED。

請注意,從 12c(數據庫和驅動程序)開始,您可以獲得批次中每個元素的更新計數。 當您批量執行更新時,這更有用。 對於批處理中的每個元素,您可以知道更新了多少行。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM