In this tutorial you will learn how to move cursor in JDBC ResultSet object
In this tutorial you will learn how to move cursor in JDBC ResultSet objectThere are many methods are given to move within result set. They makes easy to read data within result set. An example given below which illustrates those methods.
MovingCursorWithinResultSet.java
package roseindia.net;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class MovingCursorWithinResultSet {
public static void main(String[] args) throws SQLException {
Connection connection = null; // connection reference variable for getting
// connection
Statement statement = null; // Statement reference variable for query
// Execution
ResultSet resultSet = null; // ResultSet reference variable for saving query
// result
String conUrl = "jdbc:mysql://localhost:3306/";
String driverName = "com.mysql.jdbc.Driver";
String databaseName = "student";
String usrName = "root";
String usrPass = "root";
try {
// Loading Driver
Class.forName(driverName);
} catch (ClassNotFoundException e) {
System.out.println(e.toString());
}
try {
// Getting Connection
connection = DriverManager.getConnection(conUrl + databaseName, usrName,
usrPass);
// Getting reference to connection object
statement = connection.createStatement(ResultSet.TYPE_FORWARD_ONLY,ResultSet.CONCUR_READ_ONLY);
// creating Query String
String query = "SELECT * FROM student";
// excecuting query
resultSet = statement.executeQuery(query);
// Getting Results ifrom ForWard only direction
System.out.println("Moving Forward");
while (resultSet.next()) {
// Didplaying data of tables
System.out.println("Roll No " + resultSet.getInt("RollNo") + ", Name "
+ resultSet.getString("Name") + ", Course "
+ resultSet.getString("Course") + ", Address "
+ resultSet.getString("Address"));
}
resultSet.afterLast();
System.out.println("\nMoving in BackWard Direction");
while(resultSet.previous()){
System.out.println("Roll No " + resultSet.getInt("RollNo") + ", Name "
+ resultSet.getString("Name") + ", Course "
+ resultSet.getString("Course") + ", Address "
+ resultSet.getString("Address"));
}
} catch (Exception e) {
System.out.println(e.toString());
} finally {
// Closing connection
resultSet.close();
statement.close();
connection.close();
}
}
}
When you run this application it will display message as shown below:| Moving Forward Roll No 1, Name Rajan, Course MCA, Address Motihari Roll No 3, Name Rohan, Course MCA, Address Mumbai Moving in BackWard Direction Roll No 3, Name Rohan, Course MCA, Address Mumbai Roll No 1, Name Rajan, Course MCA, Address Motihari |