How to move the cursor through a result set

Methods of a ResultSet object that work with a result set

Methods Description
beforeFirst() Moves the cursor to the front of this ResultSet object, just before the first row
afterFirst() Moves the cursor to the end of this ResultSet object, just after the last row
first() Moves the cursor to the first row in this ResultSet object
previous() Moves the cursor to the previous row in this ResultSet object
next() Moves the cursor froward one row from its current position
last() Moves the cursor to the last row in this ResultSet object
absolute(intRow) Moves the cursor to the given row number in this ResultSet object
relative(intRow) Moves the cursor a relative number of rows, either positive or negative. Attempting to move beyond the first/last row in the result set positions the cursor before/after the the first/last row. Calling relative(0) is valid, but does not change the cursor position.
isBeforeFirst() Retrieves whether the cursor is before the first row in this ResultSet object
isAfterLast() Retrieves whether the cursor is after the last row in this ResultSet object
isFirst() Retrieves whether the cursor is on the first row of this ResultSet object
isLast() Retrieves whether the cursor is on the last row of this ResultSet object. Note: Calling the method isLast may be expensive because the JDBC driver might need to fetch ahead one row in order to determine whether the current row is the last row in the result set
close() Releases this ResultSet object's database and JDBC resources immediately instead of waiting for this to happen when it is automatically closed
getRow() Retrieves the current row number

How to work with a forward-only result set

while(rs.next())
{
// code that works with each record
}

How to work with a scrollable result set

rs.first()
rs.last()
if (rs.isFirst() == false)
rs.previous();
if (rs.isLast() == false)
rs.next();
rs.absolute(4);
rs.relative(-2);
rs.relative(3);

Description:

  • The first, previous, next, last, absolute and relative methods all return a true value if the new row exists and a false value if the new row doesn't exist or the result set is empty.
  • All of the methods in this figure throw an exception of the SQLException type.

More info can be found here: http://www.j2ee.me/javase/6/docs/api/java/sql/ResultSet.html