How to get row count using ResultSet in Java?

前端 未结 13 2133
[愿得一人]
[愿得一人] 2020-11-27 13:05

I\'m trying to create a simple method that receives a ResultSet as a parameter and returns an int that contains the row count of the ResultSet. Is this a valid way of doing

13条回答
  •  鱼传尺愫
    2020-11-27 13:31

    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_rows
    FROM my_table
    WHERE ...
    

提交回复
热议问题