cac*_*ert 5 java oracle jdbc batch-processing
我有一个 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;
Run Code Online (Sandbox Code Playgroud)
假设您有 5 个批量更新语句。它们每个的执行都是更新20条记录,这是预先知道的。
批量更新语句的执行不会抛出BatchUpdateException, 或SQLException。
如果返回的 int 数组中的任何元素不是 20,那么您就知道出现了意外行为。这可以被视为失败。
编辑
来自BatchUpdateExcpetion 的JavaDoc(重点是我的补充)
批处理更新中的命令无法正确执行并引发 BatchUpdateException 后,驱动程序可能会也可能不会继续处理批处理中的其余命令。如果驱动程序在失败后继续处理,则 BatchUpdateException.getUpdateCounts 方法返回的数组将包含批处理中每个命令的元素,而不是仅包含错误之前成功执行的命令的元素。在驱动程序停止[ed]处理命令的情况下,任何失败命令的数组元素都是Statement.EXECUTE_FAILED。
我对此的理解是,如果批处理中的任何BatchUpadteException语句失败,则会抛出 a 。