Java mysql jdbc多次更新返回错误的受影响行
表Java mysql jdbc多次更新返回错误的受影响行,java,mysql,jdbc,Java,Mysql,Jdbc,表t\u test包含两列:id和createDate,我在jdbc url中设置allowMultiQueries=true。 在上面的sql中,更新了两行,但是preparedStatement.getUpdateCount()返回1。 MySQL服务器版本是5.7,我用jdbc驱动程序版本5.1.40、6.0.6和8.0.21进行了测试,它们都返回相同的结果:1 编辑: 正如@Massimo所说,我反复使用getMoreResults()和getUpdateCount()来获取更新的计数,
t\u test
包含两列:id
和createDate
,我在jdbc url中设置allowMultiQueries=true
。
在上面的sql中,更新了两行,但是preparedStatement.getUpdateCount()
返回1。
MySQL服务器版本是5.7,我用jdbc驱动程序版本5.1.40、6.0.6和8.0.21进行了测试,它们都返回相同的结果:1
编辑
:
正如@Massimo所说,我反复使用getMoreResults()
和getUpdateCount()
来获取更新的计数,并将它们相加,直到getUpdateCount()
返回-1
代码如下:
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();
无法测试它。
但是从理论上讲,当您执行多个语句时,preparedStatement
会返回每个语句的updateCount。
它给出了第一条语句的更新计数。要获取秒的更新计数,您应该尝试调用preparedStatement.getMoreResults()
,然后再次调用preparedStatement.getUpdateCount()
见文件
使用多个查询时,它很可能返回执行的第一次(或可能是最后一次)更新的更新计数。不要使用多重查询。它是JDBC API的非标准扩展。@MarkRotterVeel,getUpdateCount()返回第一个语句结果。解决这个问题的正确方法仍然写在OP.Tks的编辑部分。很高兴听到您有一个解决方案,但是,在一次执行中执行多个查询并不是JDBC的使用方式。Tks非常多。我接受了你的建议,在OP的编辑部分写了代码,它很有效。
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);