如何在 JDBC 中获取行数? [英] How do I get the row count in JDBC?

查看:34
本文介绍了如何在 JDBC 中获取行数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已执行 JDBC 查询以获取结果集.在迭代之前,我想快速找出返回了多少行.我怎样才能以高性能来做到这一点?

I've executed a JDBC query to obtain a resultset. Before iterating over it, I'd like to quickly find out how many rows were returned. How can I do this with high performance?

我使用的是 Java 6、Oracle 11g 和最新的 Oracle JDBC 驱动程序.

I'm using Java 6, Oracle 11g, and the latest Oracle JDBC drivers.

推荐答案

您将不得不将此作为单独的查询来执行,例如:

You're going to have to do this as a separate query, for example:

SELECT COUNT(1) FROM table_name

某些 JDBC 驱动程序可能会告诉您,但这是可选行为,更重要的是,驱动程序可能还不知道.这可能是由于查询是如何优化的,例如 Oracle 中的两个示例执行策略是尽快获取所有行或尽快获取第一行.

Some JDBC drivers might tell you but this is optional behaviour and, more to the point, the driver may not know yet. This can be due to how the query is optimised eg two example execution strategies in Oracle are to get all rows as quickly as possible or to get the first row as quickly as possible.

如果您执行两个单独的查询(一个是计数,另一个是查询),那么您需要在同一个事务中执行它们.这在 Oracle 上运行良好,但在其他数据库上可能会出现问题(例如,SQL Server 将根据您的隔离级别向您显示未提交的数据或阻止外部未提交的更新,而 Oracle 支持的隔离级别可为您提供事务上一致的视图数据而不会阻止外部更新).

If you do two separate queries (one a count and the other the query) then you'll need to do them within the same transaction. This will work well on Oracle but can be problematic on other databases (eg SQL Server will either show you uncommitted data or block on an external uncommitted update depending on your isolation level whereas Oracle supports an isolation level that gives you a transactionally consistent view of the data without blocking on external updates).

通常情况下,有多少行并不重要.通常,这种查询要么是批处理的,要么是分页的,无论哪种方式,您都可以以加载/处理的行的形式获得进度信息,并且您可以检测到结果集的结尾(显然).

Normally though it doesn't really matter how many rows there are. Typically this sort of query is either batch processed or paged and either way you have progress information in the form of rows loaded/processed and you can detect the end of the result set (obviously).

这篇关于如何在 JDBC 中获取行数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆