How to move the result set pointer to required position?


The absolute() method of the ResultSet interface accepts an integer value representing the index of a row and moves the ResultSet pointer of the current ResultSet object to the specified position.

Assume we have a table named cricketers_data with 6 records as shown below:

+------------+------------+---------------+----------------+-------------+
| First_Name | Last_Name  | Date_Of_Birth | Place_Of_Birth | Country     |
+------------+------------+---------------+----------------+-------------+
| Shikhar    | Dhawan     | 1981-12-05    | Delhi          | India       |
| Jonathan   | Trott      | 1981-04-22    | CapeTown       | SouthAfrica |
| Lumara     | Sangakkara | 1977-10-27    | Matale         | Srilanka    |
| Virat      | Kohli      | 1987-04-30    | Delhi          | India       |
| Rohit      | Sharma     | 1987-04-30    | Nagpur         | India       |
| Ravindra   | Jamnagar   | 1988-12-06    | NULL           | India       |
+------------+------------+---------------+----------------+-------------+

Following JDBC program establishes a connection with the database, retrieves the contents of the cricketers_data table into a ResultSet object and, moves the pointer to 3rd row and prints its contents:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class ResultSet_DeletingRow {
   public static void main(String args[])throws Exception {
      //Registering the Driver
      DriverManager.registerDriver(new com.mysql.jdbc.Driver());
      //Getting the connection
      String mysqlUrl = "jdbc:mysql://localhost/mydatabase";
      Connection con = DriverManager.getConnection(mysqlUrl, "root", "password");
      System.out.println("Connection established......");
      //Creating a Statement object
      Statement stmt = con.createStatement();
      //Query to retrieve the contents of the employee_data table
      String query = "select * from cricketers_data";
      //Executing the query
      ResultSet rs = stmt.executeQuery(query);
      //Moving ResultSet object to the required position
      rs.absolute(3);
      //Contents of the current row
      System.out.println("First name: "+rs.getString(1));
      System.out.println("Last name: "+rs.getString(2));
      System.out.println("Date of birth: "+rs.getDate(3));
      System.out.println("Place of birth: "+rs.getString(4));
      System.out.println("Country: "+rs.getString(5));
   }
}

Output

Connection established......
First name: Lumara
Last name: Sangakkara
Date of birth: 1977-10-27
Place of birth: Matale
Country: Srilanka

Updated on: 30-Jul-2019

167 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements