I have used a ResultSet
that returns certain number of rows. My code is something like this:
ResultSet res = getData(); if(!res.next()) { System.out.println("No Data Found"); } while(res.next()) { // code to display the data in the table. }
Is there any method to check the number of rows returned by the ResultSet
? Or do I have to write my own?
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 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.
To number rows in a result set, you have to use an SQL window function called ROW_NUMBER() . This function assigns a sequential integer number to each result row. However, it can also be used to number records in different ways, such as by subsets.
The SQL COUNT() function returns the number of rows in a table satisfying the criteria specified in the WHERE clause. It sets the number of rows or non NULL column values. COUNT() returns 0 if there were no matching rows.
First, you should create Statement
which can be move cursor by command:
Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
Then retrieve the ResultSet
as below:
ResultSet rs = stmt.executeQuery(...);
Move cursor to the latest row and get it:
if (rs.last()) { int rows = rs.getRow(); // Move to beginning rs.beforeFirst(); ... }
Then rows variable will contains number of rows returned by sql
You could use a do ... while
loop instead of a while
loop, so that rs.next()
is called after the loop is executed, like this:
if (!rs.next()) { //if rs.next() returns false //then there are no rows. System.out.println("No records found"); } else { do { // Get data from the current row and use it } while (rs.next()); }
Or count the rows yourself as you're getting them:
int count = 0; while (rs.next()) { ++count; // Get data from the current row and use it } if (count == 0) { System.out.println("No records found"); }
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