How to find number of rows in the ResultSet object?


Number of rows in table JDBC

There is no direct method in JDBC. In JDBC 1.0, the only way available is using while loop with a counter as follows.

Example on number of rows in table JDBC with JDBC 1.0 style
ResultSet res = stmt.executeQuery("select * from Employee");

int counter = 0;
while(res.next())
{
  counter++;
}
System.out.println("Number of records in ResultSet: " + counter);

You used the above loop in Select Records

By coding logic using JDBC 2.0 API ResultSet methods, the above loop is not required and the coding becomes very simple with two method calls last() and getRow() as follows.

Example on number of rows in table JDBC with JDBC 2.0 style methods
ResultSet res = stmt.executeQuery("select * from Employee");
res.last();                         // record pointer is placed on the last row
int counter = res.getRow();
System.out.println("Number of records in ResultSet: " + counter);

last() method places the record pointer (or cursor) on the last record. getRow() returns the row number. This is tricky code.

Note: Before using above code, check your driver support JDBC 2.0 API methods else you may get SQLException or some compilation error.

If you are required to find the number of rows frequently in the code by all the team members, better write a method with a similar code like this.

public static int getNumOfRows(ResultSet res) throws SQLException  
{  
   int currentRow = res.getRow();   
   int counter = res.last() ? res.getRow() : 0;
   if (currentRow == 0)                      
      res.beforeFirst();                  
   else                                      
      res.absolute(currentRow);              

   return counter;  
}  

Let us explain the code for a novice.

res.getRow() returns row number of the current row (where the cursor exists right now). It may be required in future code to place the cursor on the current row after doing all the operations on the cursor (or ResultSet object)
res.last() places the cursor on the last row. You used this in Creating Scrollable ResultSet
if (currentRow == 0) if no records exist
res.beforeFirst() place the cursor before the first record so that you can enter records further. This makes user friendly software
else if there are records
res.absolute(currentRow) place the cursor on the current record, the record from where you tried to find the number of records

(many software companies make routines like this and creates their own API).

3 thoughts on “How to find number of rows in the ResultSet object?”

  1. JDBC 1.0 style is worked for me….I am searching for this solution since a day ….now i got exact solution ….Thank you so much

Leave a Comment

Your email address will not be published.