Java java.sql.ResultSet
How to determine the size of an object
In Java, database operations often involve processing result sets. However, determining the size of a ResultSet is a common problem.
Unlike expected, java.sql.ResultSet
does not directly provide functions such as size()
or length()
to get the number of rows in the result set.
Method 1: Use SELECT COUNT(*) to query
The most straightforward approach is to execute a separate SELECT COUNT(*) FROM ...
query against the same table that generated the original ResultSet. This query returns the total number of rows in the table, which can be used as a proxy for the ResultSet size.
Method 2: Use rs.last() and getRow()
Alternatively, you can use the following code snippet:
<code class="language-java">int size = 0; if (rs != null) { rs.last(); // 将游标移动到最后一行 size = rs.getRow(); // 获取行号 }</code>
This method moves the cursor to the last row of the ResultSet and retrieves the row identifier, effectively providing the size of the ResultSet.
Both methods can efficiently determine the size of the ResultSet without having to iterate through all rows, saving valuable time and resources.
The above is the detailed content of How Can I Efficiently Determine the Number of Rows in a Java `java.sql.ResultSet`?. For more information, please follow other related articles on the PHP Chinese website!