1

我将计算受查询影响的行数,该查询作为传递给 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。

4

1 回答 1

0
  1. 检查返回的内容select * from Activity where ActivityName=?

  2. 检查返回的内容select ... where ... (select ...)

在您在评论中解释您的目标之后,还有其他解决方案可以添加尚不存在的值。

  1. 定义列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
    }

为什么不先检查这样的 ActivityName 是否已经存在?因为如果您有来自同一用户或许多其他用户的并行请求,那么在您检查之间和插入新值之间的时间里,其他请求可以插入该值,并且您会得到主键违规异常。这就是为什么您需要以任何方式尝试/捕获的原因。这就是为什么只插入而不进行任何检查并使用正确的 try/catch 的原因。

于 2019-09-05T19:50:56.783 回答