How to Navigate through a ResultSet using a JDBC program?

The next() method of the ResultSet interface moves the pointer/Cursor of the current ResultSet object to the next row from the current position. This method returns a boolean value. If there are no rows next to its current position this method returns false, else it returns true.

Therefore, using this method in the while loop you can iterate the contents of the ResultSet object.


Getting the column values of each record

The ResultSet interface (also) provides getter methods (getXXX()) to retrieve values in each column of a row, each getter methods has two variants:

  • getXXX(int columnIndex): Accepts an integer value representing the index of the column and returns its value.

  • getXXX(String columnLabel ): Accepts a String value representing the name of the column and returns its value.

You need to use the respective getter method based on the datatype of the column in the table.

while( {
   System.out.print("Brand: "+rs.getString("Column_Name")+", ");
   System.out.print("Sale: "+rs.getString("Column_Name "));

In the same way if it is a bi-directional ResultSet object you can navigate backwards using the previous() method.

Since the pointer of the ResultSet object is positioned before 1st row by default. To navigate backwards you need to shift the pointer/cursor to the next row after the last and, navigate backwards as:


System.out.println("Contents of the table");
while(rs.previous()) {
   System.out.print("Brand: "+rs.getString("Mobile_Brand")+", ");
   System.out.print("Sale: "+rs.getString("Unit_Sale"));

Updated on: 30-Jul-2019


Kickstart Your Career

Get certified by completing the course

Get Started