gpt4 book ai didi

java - 部分失败时的 executeBatch 行为

转载 作者:搜寻专家 更新时间:2023-11-01 03:50:09 27 4
gpt4 key购买 nike

我有一个 Java 1.6 应用程序,它使用批插入在使用 jdbc 驱动程序的 Oracle 数据库中插入记录。如您所知,在 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,那么您就知道发生了意外行为。这可以被视为失败。

编辑

来自JavaDoc BatchUpdateExcpetion的(亮点是我添加的)

After a command in a batch update fails to execute properly and a BatchUpdateException is thrown, the driver may or may not continue to process the remaining commands in the batch. If the driver continues processing after a failure, the array returned by the method BatchUpdateException.getUpdateCounts will have an element for every command in the batch rather than only elements for the commands that executed successfully before the error. In the case where the driver stops [ed] processing commands, the array element for any command that failed is Statement.EXECUTE_FAILED.

我的理解是,如果批处理中的任何语句失败,则会抛出BatchUpdteException

关于java - 部分失败时的 executeBatch 行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30867059/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com