我会计算受查询影响的行数,该查询作为传递给 MySql 引擎的 java 中的准备语句提供。
给定以下示例查询传递给准备好的语句,我需要能够计算受所有查询影响的总行数。
//insert data into table X ;
//update records of table X ;
查询以“;”分隔这是 MySql 语法的一部分,用于支持对特定 PreparedStatement 对象的多个 CRUD 操作。 似乎在调用“executeUpdate()”方法时,返回的只是受第一个查询(即插入表)影响的行数。 我是否遗漏了我应该提供的内容以获取此类查询中受影响的总行数?
这是我正在处理的示例真实代码:
insert into Activity
select * from (select ?, ?, ?, ?) as temp
where not exists(select * from Activity where ActivityName=?);
update Activity
set EmployeeeName=?, DepartmentName=?, roleId=?
where ActivityName=?;
我期望最小值 1 作为输出,而得到 0。
最佳答案
检查什么返回
select * from Activity where ActivityName=?
。检查什么返回
select ... where ... (select ...)
。
在您在评论中解释您的目标后,还有其他解决方案可以增加尚不存在的值(value)。
- 定义列
ActivityName
是一个主键(如果没有做是)。然后不检查任何东西,不做任何select
,只做insert
:
try {
// statement to insert like
// insert into Activity (ActivityName, EmployeeeName, DepartmentName, roleId)
// values (?, ?, ?, ?)
} catch ... {
// If the exception is caused by primary key violation,
// then such ActivityName already existed and we can ignore this exception
}
为什么不先检查这样的 ActvityName 是否已经存在?因为如果您有许多来自同一用户或许多其他用户的并行请求,那么在您检查和插入新值之间的时间里,其他一些请求可以插入该值,并且您会遇到主键冲突异常。这就是为什么你需要以任何方式尝试/捕捉。这就是为什么只进行插入而不进行任何检查并使用正确的 try/catch 的原因。
关于java - 计算在 java 代码中传递给 MySql 的几个查询中受影响的行数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57778344/