Get Number of Rows returned by ResultSet in Java

Kiran picture Kiran · Nov 28, 2011 · Viewed 246.5k times · Source

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

Tu Tran picture Tu Tran · Nov 28, 2011

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