部分失败时的executeBatch行为

我有一个java 1.6应用程序,它使用批量插入来使用jdbc驱动程序在Oracle数据库中插入记录。 正如您在Statement对象上所知,有一个名为executeBatch()的方法,我们将其用于批量更新。 它有一个返回类型的int数组,其中包含每个记录的执行结果。 但它也会在出现错误时抛出BatchUpdateException,我们也可以从中获取结果int数组。 我的问题是我应该期待什么样的错误情况BatchUpdateException和什么时候我应该期望没有抛出exception但是对于某些记录我得失败。

注意:问题特别针对Oracle JDBC。 为了更清楚,我已经看到在执行executeBatch()之后的情况我没有得到BatchUpdateException,但是一些insert语句失败了。 我的问题是关于可能发生的情况?

这是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. * 

*

    *
  1. 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.
  2. *
  3. If the value is SUCCESS_NO_INFO, the command completed * successfully but the number of rows affected is unknown. *
  4. *
  5. If the value is EXECUTE_FAILED, the command failed. *
* @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(数据库和驱动程序)开始,您可以获得批处理的每个元素的更新计数。 当您批量执行更新时,这更有用。 对于批处理中的每个元素,您可以知道已更新的行数。