简体   繁体   English

Java JDBC batchExecute插入

[英]Java JDBC batchExecute insert

I am using JDBC addBatch and batchExecute for insert statements. 我将JDBC addBatch和batchExecute用于插入语句。 I have autocommit mode to on. 我已启用自动提交模式。 My problem is, when I have for example 20 inserts, and insert number 10 raises an exception (for example null values not allowed), no data is inserted. 我的问题是,例如,当我有20个插入,而插入编号10引发异常(例如,不允许使用空值)时,则不会插入任何数据。 Shouldn't be the first 10 ok statements be inserted?. 不应该插入前10个ok语句吗?

My code: 我的代码:

        try {
            int[] results =  stmt.executeBatch();                
            return results;
        } catch (BatchUpdateException e) {
            int[] tmpres = e.getUpdateCounts();                
            for (i = 0; i < tmpres.length; i++) {
                System.out.println(tmpres[i]);
            }
        }

I see on the output that the update count of the first 10 statements is 1. So why no data is inserted? 我在输出中看到前10条语句的更新计数为1。那么为什么不插入数据呢?

Best regards, Peter 最好的问候,彼得

The other answers to this question are somewhat misleading, at least with regard to the general case. 至少在一般情况下,这个问题的其他答案有些误导。

In most cases, when using executeBatch() with setAutoCommit(true) : 在大多数情况下,将executeBatch()setAutoCommit(true)

  • the statements in the batch are not wrapped in an implicit transaction, and 批处理中的语句包装在隐式事务中,并且
  • the statements processed prior to the BatchUpdateException will be committed. 在BatchUpdateException之前处理的语句被提交。

This is definitely true for MySQL Connector/J (with rewriteBatchedStatements=false , which is the default), the Microsoft SQL Server JDBC driver, Derby, and HSQLDB. 对于MySQL Connector / J(默认rewriteBatchedStatements=false ),Microsoft SQL Server JDBC驱动程序,Derby和HSQLDB,绝对是正确的。 (I just ran actual Java code to confirm.) (我只是运行实际的Java代码进行确认。)

As with many other aspects of JDBC, the actual behaviour in your particular case depends on the specific implementation of the JDBC driver you are using. 与JDBC的许多其他方面一样, 您的特定情况下的实际行为取决于您所使用的JDBC驱动程序的特定实现。

Seems like in your configuration, all the statements inside one batch are in fact executed in one transaction . 似乎在您的配置中,实际上一批内的所有语句都在一个事务中执行。 So if any of the inserts fail, the whole transaction (that's the whole batch) will be rolled back. 因此,如果任何插入失败,整个事务(即整个批次)将被回滚。 Even with autocommit on. 即使启用了自动提交。

在这种情况下, 所有语句都包含在同一事务中,因此任何会导致错误的语句都会回滚整个事务。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM