How to get row count using ResultSet in Java? How to get row count using ResultSet in Java? java java

How to get row count using ResultSet in Java?


If you have access to the prepared statement that results in this resultset, you can use

connection.prepareStatement(sql,   ResultSet.TYPE_SCROLL_INSENSITIVE,   ResultSet.CONCUR_READ_ONLY);

This prepares your statement in a way that you can rewind the cursor. This is also documented in the ResultSet Javadoc

In general, however, forwarding and rewinding cursors may be quite inefficient for large result sets. Another option in SQL Server would be to calculate the total number of rows directly in your SQL statement:

SELECT my_table.*, count(*) over () total_rowsFROM my_tableWHERE ...


your sql Statement creating code may be like

statement = connection.createStatement();

To solve "com.microsoft.sqlserver.jdbc.SQLServerException: The requested operation is not supported on forward only result sets" exception change above code with

statement = connection.createStatement(    ResultSet.TYPE_SCROLL_INSENSITIVE,     ResultSet.CONCUR_READ_ONLY);

After above change you can use

int size = 0;try {    resultSet.last();    size = resultSet.getRow();    resultSet.beforeFirst();}catch(Exception ex) {    return 0;}return size;

to get row count


Statement s = cd.createStatement();ResultSet r = s.executeQuery("SELECT COUNT(*) AS rowcount FROM FieldMaster");r.next();int count = r.getInt("rowcount");r.close();System.out.println("MyTable has " + count + " row(s).");

Sometimes JDBC does not support following method gives Error like `TYPE_FORWARD_ONLY' use this solution

Sqlite does not support in JDBC.

resultSet.last();size = resultSet.getRow();resultSet.beforeFirst();

So at that time use this solution.