首页 > 解决方案 > mysql jdbc 多更新返回错误的受影响行

问题描述

    String sql = "update t_test set createDate = now() where id = 1; update t_test set createDate = now() where id = 101;";
    String url = "jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true&useSSL=false";
    Connection connection = DriverManager.getConnection(url, "username", "password");
    connection.setAutoCommit(false);
    final PreparedStatement preparedStatement = connection.prepareStatement(sql);
    preparedStatement.execute();
    //return 1, but 2 rows actually updated
    System.out.println("updated rows=" + preparedStatement.getUpdateCount());
    connection.commit();
    connection.close();

t_test包含两列:idcreateDate,我allowMultiQueries=true在 jdbc url 中设置。在上面的sql中,更新了两行,但是preparedStatement.getUpdateCount()返回1。 MySQL服务器版本是5.7,我用jdbc驱动版本5.1.40、6.0.6和8.0.21测试过,它们都返回相同的结果:1

EDIT:正如@Massimo 所说,我反复使用getMoreResults()andgetUpdateCount()来获取更新的计数并将它们相加,直到getUpdateCount()返回-1。

代码如下:

    System.out.println("updated rows=" + preparedStatement.getUpdateCount());
    int totalCount = preparedStatement.getUpdateCount();
    while (true){
        preparedStatement.getMoreResults();
        final int updateCount = preparedStatement.getUpdateCount();
        if(updateCount != -1){
            System.out.println("updated rows=" + preparedStatement.getUpdateCount());
            totalCount += preparedStatement.getUpdateCount();
        }else{
            break;
        }
    }
    System.out.println("total updated rows=" + totalCount);

标签: javamysqljdbc

解决方案


无法测试它。但是理论上,当您执行多个语句时,preparedStatement会返回每个语句的 updateCount。所以它给出了第一条语句的更新计数。要获得第二个的更新计数,您应该尝试调用preparedStatement.getMoreResults()然后再调用preparedStatement.getUpdateCount()一次。

见文档

https://docs.oracle.com/javase/7/docs/api/java/sql/Statement.html#getUpdateCount()

https://docs.oracle.com/javase/7/docs/api/java/sql/Statement.html#getMoreResults()


推荐阅读