在executeBatch()之后使用CallableStatement检索ResultSet

时间:2014-01-14 16:32:01

标签: java jdbc

我需要多次调用存储过程并使用executeBatch()。每次调用都应返回包含结果的表,但我无法访问此结果。下一个代码工作正常:

callableStatement.setString(1, "foo");
callableStatement.setString(2, "bar");
callableStatement.execute();
resultSet = callableStatement.getResultSet();

但是下一个代码没有按预期工作:

for (String str : strings) {
    callableStatement.setString(1, str);
    callableStatement.setString(2, "bar");
    callableStatement.addBatch();
}
callableStatement.executeBatch();
resultSet = callableStatement.getResultSet(); // returns null

在提取ResultSet之前,我已尝试调用callableStatement.getUpdateCount()callableStatement.getMoreResults(),但未成功。

1 个答案:

答案 0 :(得分:4)

这不是#executeBatch的正确用法。批处理方法用于执行数据操作,而不是获取结果数据。也就是说,您可以进行批量插入/更新/删除但不能读取。 #executeBatch的结果是更新计数,表示每个批处理操作进行了多少更改

目的是通过减少网络开销和数据库往返来实现类似的数据操作操作,从而提高性能。

您通常不会批处理执行查询,因为不同的查询会导致不同形状的ResultSet s(除非它们都是针对具有相同列但具有不同查询的同一个表[但为什么不仅仅修改您的查询])。