Search code examples
javajdbcresultset

Get RowCount from a ResultSet after a few next() calls


I have the following code:

//rs is a ResultSet from a prepared statement
rs.last();
this.resultCount = rs.getRow();
rs.beforeFirst();

If I execute that code after i executed a few rs.next(), then the rs.beforeFirst() is wrong.

So my question is: how can I get back to the current position and not to the beforeFirst position?


Solution

  • Question: "how can I get back to the current position and not to the before the first position."

    Answer: You can use resultSet.absolute(rowIndex);


    Detailed explanation:
    Moves the cursor to the given row number in this ResultSet object.
    If the row number is positive, the cursor moves to the given row number with respect to the beginning of the result set. The first row is row 1, the second row 2, and so on.

    If the given row number is negative, the cursor moves to an absolute row position with respect to the end of the result set. For example, calling the method absolute(-1) positions the cursor on the last row; calling the method absolute(-2) moves the cursor to the next-to-last row, and so on.

    If the row number specified is zero, the cursor is moved to before the first row.


    However, you can use absolumte(rowIndex) in your program such as,

    int currRowIndex = resultSet.getRow();
    resultSet.last(); // <- can throw if resultSet type is TYPE_FORWARD_ONLY
    this.resultCount = resultSet.getRow();
    resultSet.absolute(currRowIndex); // <- It will allow you to set cursor position.
    

    Warning: When the use of last() it can throw if the resultSet type is TYPE_FORWARD_ONLY.

    last
    boolean last() throws SQLException
    Moves the cursor to the last row in this ResultSet object.<be>
    
    Returns:
     - true if the cursor is on a valid row;
     - false if there are no rows in the result set
    
    Throws:
     - SQLException: if a database access error occurs; this method is called on a closed result set or the result set type is TYPE_FORWARD_ONLY
    
     - SQLFeatureNotSupportedException: if the JDBC driver does not support
       this method