java - 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
包含两列:id
和createDate
,我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);
解决方案
无法测试它。但是理论上,当您执行多个语句时,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()
推荐阅读
- google-apps-script - 将文件从网络上传到 Google 云端硬盘
- c - #define 中的换行符和单双引号
- python - 使用 slice 来迭代列表
- angular - 如何在 Input Angular Decorator 中使用 Observable?
- javascript - NodeJS SQL登录错误(ERR_HTTP_HEADERS_SENT]:发送到客户端后无法设置标头)
- monaco-editor - Monaco 编辑器是否支持 xml 模式验证?
- react-native - expo 上的 webgl 纹理给出了黑屏
- postgresql - 使用 AWS CLI 创建 AWS aurora postgres 实例的正确参数是什么?
- r - 如何在ggplot中手动在图例下方添加文本?
- python - AWS CodeBuild 彩色日志