java - 使用 BatchUpdateExcpetion 处理 JDBC BatchUpdate 异常

标签 java mysql jdbc exception

我正在尝试使用批量更新来更新表中的数据。当我更新数据时,出现了一些失败。我想获取失败查询的更新语句。例如,如果失败的查询是“update table set abc= 123”。然后我希望异常处理程序返回此 SQL 查询。

我尝试了多种方法来获取 SQL 查询,但我无法做到这一点。

下面是代码:

 String line=null;
 int cnt=0;
 int batchSize=100;
 BufferedReader br2=new BufferedReader(new FileReader("clean.txt"));
 stmt1=conn.createStatement();
 while((line = br2.readLine()) != null)
 {
    try {
        String sql = line;
           stmt1.addBatch(sql);
         //System.out.println(cnt);
           if(++cnt % batchSize == 0)
           {
               stmt1.executeBatch();
               conn.commit();
           }                           
        } 
    catch (BatchUpdateException ex) {
        System.out.println(ex.getLocalizedMessage());
                 int[] updateCount = ex.getUpdateCounts();
                    int cnt1 = 1;
                    for (int i : updateCount) {
                        if  (i == Statement.EXECUTE_FAILED) {
                            System.out.println("Error on request " + cnt1 +": Execute failed");
                      } else {
                            System.out.println("Request " + cnt1 +": OK");
                        }
                        cnt1++;
                    } 
                }
}
System.out.println("done");
br2.close();

请让我知道我该怎么做才能获取失败的 SQL 查询。因此,如果我有查询,我可以再次将其存储在文件中。

最佳答案

getUpdateCounts 的确切含义取决于驱动程序实现:JDBC 规范允许它包含第一次失败之前成功执行的语句的更新计数,或者它包含所有执行的语句,其中失败标记为 EXECUTE_FAILED 值;来自BatchUpdateException :

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 continues processing commands, the array element for any command that failed is Statement.EXECUTE_FAILED.

换句话说,如果你想知道失败的语句,有两种情况需要处理:

  1. 更新计数数组的长度小于批处理语句的数量。
    在这种情况下,第一个(数组长度)语句已成功执行。语句(数组长度) + 1失败,其余语句尚未执行。
  2. 数组的长度等于批处理语句的数量。
    在这种情况下,您可以迭代数组,所有值为 Statement.EXECUTE_FAILED 的索引都是失败的语句。

对于这两种情况,您都需要进行簿记以跟踪批处理中的语句并将它们与失败和/或未执行语句的索引进行匹配。

关于java - 使用 BatchUpdateExcpetion 处理 JDBC BatchUpdate 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39621679/

相关文章:

java - 是否建议在 java 中使用 PreparedStatement.setBoolean(1, Boolean.TRUE)?

java - 如何更改对象的不透明度

java - Java 中 i +"abc"的类型

java - 如何从不同的 MySQL 表中获取特定的 id

java - 使用 jdbcTemplate 优化选择创建

java - Ehcache 集群需要很长时间才能在 Tomcat 上启动

php - Mysql WHERE列在字符串中

mysql - Magento 通过 phpmyadmin 删除禁用的产品

java - 使用 Apache Spark 将每个组的前 2 行与 Java 展平

database - 与 Derby 数据库交互时我的应用程序中的 SQLNonTransientConnectionException : No current connection,