Kiran Kiran - 4 months ago 10
Java Question

Get Number of Rows returned by ResultSet in Java

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?

Answer

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");
}