How to Scroll Result Set in Java


In this example we will show how to scroll result set with the cursor.

Source Code

package com.beginner.examples;

import com.mysql.jdbc.Driver;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
  
    public class ScrollableResultExample {
        public static void main(String[] args) throws SQLException, ClassNotFoundException {

        Class.forName("com.mysql.jdbc.Driver");
        
        //database connection
        Connection conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/mysql", "root", "");

        // sql statement
        String sql = "SELECT host from user " +
                " WHERE user = 'root' ";

        try
        {
        	// execute sql statement
        	ResultSet rs = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
                    ResultSet.CONCUR_READ_ONLY).executeQuery(sql);
            while (rs.next()) 
            {
            	System.out.println(rs.getString(1));
            }
            //previous record
            while(rs.previous())
            {
                System.out.println(rs.getString(1));
            }
        }
        catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

Output:

127.0.0.1
::1
localhost
localhost
::1
127.0.0.1

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments