How to move the pointer of a ResultSet to the end of the table using JDBC?



The afterLast() method of the ResultSet interface moves the cursor/pointer after the last row of the ResultSet object.

rs.afterLast();

Assume we have a table name dataset as shown below:

+--------------+-----------+ | mobile_brand | unit_sale | +--------------+-----------+ | Iphone       | 3000      | | Samsung      | 4000      | | Nokia        | 5000      | | Vivo         | 1500      | | Oppo         | 900       | | MI           | 6400      | | MotoG        | 4360      | | Lenovo       | 4100      | | RedMi        | 4000      | | MotoG        | 4360      | | OnePlus      | 6334      | +--------------+-----------+

Following example demonstrates the creation of bi-directional ResultSet. Here we trying to create a bi-directional ResultSet object which retrieves the data from the table name dataset and, we are trying to print rows of the dataset table from last to first.

import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; public class BidirectionalResultSet {    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/TestDB";       Connection con = DriverManager.getConnection(mysqlUrl, "root", "password");       System.out.println("Connection established......");       //Creating a Statement object       Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);       //Retrieving the data       ResultSet rs = stmt.executeQuery("select * from Dataset");       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("");       }    } }

Output

Connection established...... Contents of the table Brand: Vivo, Sale: 1500 Brand: Nokia, Sale: 5000 Brand: Samsung, Sale: 4000 Brand: IPhone, Sale: 3000
Updated on: 2019-07-30T22:30:25+05:30

140 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements