How to find number of rows in the ResultSet object?

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

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

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.

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).

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

Leave a Reply

Your email address will not be published. Required fields are marked *