How to check if resultset has one row or more with JDBC?
Getting the number of rows using methodsThe last() method of the ResultSet interface moves the cursor to the last row of the ResultSet and, the getRow() method returns the index/position of the current row.
You can use absolute to navigate to the first row: ResultSet rs = ...; rs. absolute(1); // Navigate to first row int id = rs. getInt("id"); ...
The JDBC ResultSet doesn't provide any isEmpty(), length() or size() method to check if its empty or not. Hence, when a Java programmer needs to determine if ResultSet is empty or not, it just calls the next() method and if next() returns false it means ResultSet is empty.
You can get the column count in a table using the getColumnCount() method of the ResultSetMetaData interface. On invoking, this method returns an integer representing the number of columns in the table in the current ResultSet object.
ResultSet rs = stmt.executeQuery("SELECT a, b, c FROM Table1"); boolean isMoreThanOneRow = rs.first() && rs.next();
You didn't ask this one, but you may need it:
boolean isEmpty = ! rs.first();
Normally, we don't need the row count because we use a WHILE loop to iterate through the result set instead of a FOR loop:
ResultSet rs = stmt.executeQuery("SELECT a, b, c FROM Table1"); while (rs.next()) { // retrieve and print the values for the current row int i = rs.getInt("a"); String s = rs.getString("b"); float f = rs.getFloat("c"); System.out.println("ROW = " + i + " " + s + " " + f); }
However, in some cases, you might want to window the results, and you need the record count ahead of time to display to the user something like Row 1 to 10 of 100
. You can do a separate query with SELECT COUNT(*)
first, to get the record count, but note that the count is only approximate, since rows can be added or removed between the time it takes to execute the two queries.
Sample from ResultSet Overview
There are many options, and since you don't provide more context the only thing left is to guess. My answers are sorted by complexity and performance ascending order.
select count(1) FROM ...
and get the answer. You'd have to run another query that actually selects and returns the data.rs.next()
and count until you're happy. Then if you still need the actual data re-run same query.rs.next()
couple of times and then rewind back with rs.previous()
.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With