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.

while(rs.next()){
}

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(rs.next()) {
   System.out.print("Brand: "+rs.getString("Column_Name")+", ");
   System.out.print("Sale: "+rs.getString("Column_Name "));
   ………………………
   ………………………
   System.out.println("");
}

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:

rs.afterLast();

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"));
   System.out.println("");
}

Updated on: 30-Jul-2019

136 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements