2. Scrollable Result Set
Normal Result Set allows fetching elements in forward only direction. However,
Scrollable Result Set allows us to easily move in forward/backward direction.
To create scrollable Result Set, we must use a Statement/PreparedStatement object
and provide scroll type to create Statement/prepare Statement method.
Syntax :
PreparedStatement pstmt = conn.prepareStatement (sql, Scroll type
constant, Concurrency constant);
Statement stmt = conn.createStatement(Scroll type
constant,Concurrency constant);
3. Scroll type constant
There are 3 scroll type constants can be used with ResultSets.
ResultSet.TYPE_FORWARD_ONLY
Default type.. only allows forward only fetching
ResultSet.TYPE_SCROLL_INSENSITIVE
Allows both forward and backward movement. Not sensitive to ResultSet updates.
ResultSet.TYPE_SCROLL_SENSITIVE
Allows both forward and backward movement. Not sensitive to ResultSet updates.
4. Concurrency constant
We can use following Concurrency constants for the ResultSets.
ResultSet.CONCUR_READ_ONLY
Default value .. ResultSet can not be updated.
ResultSet.CONCUR_UPDATABLE
Signifies an updatable ResultSet.
6. Example program for Scrollable
ResultSet
We have created an Employee table in local MySQL database.
In this example, we will traverse through the data retrieved from Employee table using
Scrollable ResultSet.
7. package com.topjavatutorial.jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class ScrollableResultsetDemo {
public static void main(String[] args) throws SQLException
{ String url ="jdbc:mysql://localhost:3306/TestDB";
8. String user = "userid";//add your db user id here
String password = "password";//add your db password here
Connection conn = DriverManager.getConnection(url, user, password);
System.out.println("Successfully connected");
getEmployeeData(conn); }
private static void getEmployeeData(Connection conn) throws SQLException{
String sql = "select id,name,age from employee";
try(PreparedStatement pstmt =
conn.prepareStatement(sql,ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);){ ResultSet rs = pstmt.executeQuery();
9. System.out.println("Emp Id : " + rs.getInt("id") + ", Name : " + rs.getString("name") + ", Age : " +
rs.getInt("age"));
//Last Record
rs.last();
System.out.println("Emp Id : " + rs.getInt("id") + ", Name : " + rs.getString("name") + ", Age : " +
rs.getInt("age"));
//Previous Record
rs.previous();
System.out.println("Emp Id : " + rs.getInt("id") + ", Name : " + rs.getString("name") + ", Age : " +
rs.getInt("age"));
//Next Record
rs.next();
System.out.println("Emp Id : " + rs.getInt("id") + ", Name : " + rs.getString("name") + ", Age : " +
rs.getInt("age"));
} } }
10. Output
Successfully connected
Emp Id : 8, Name : John Doe, Age : 21
Emp Id : 13, Name : James, Age : 31
Emp Id : 12, Name : James, Age : 23
Emp Id : 13, Name : James, Age : 31