Creating a Scrollable ResultSet - Java JDBC

Java examples for JDBC:ResultSet

Introduction

A scrollable ResultSet allows the results of a query to be fetched in any direction.

Demo Code

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class Main {

  public static void main(String[] args) {
    String sql = "SELECT ID, idBER, RECIPE_NAME, DESCRIPTION "
        + "FROM RECIPES";

    try (PreparedStatement pstmt = getConnection().prepareStatement(sql,
        ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        ResultSet rs = pstmt.executeQuery()) {

      rs.first();//from  w  ww  .  j  a  va 2s.  c  o  m
      System.out.println(rs.getString(2) + ": " + rs.getString(3) + " - "
          + rs.getString(4));
      rs.next();
      System.out.println(rs.getString(2) + ": " + rs.getString(3) + " - "
          + rs.getString(4));
      rs.previous();
      System.out.println(rs.getString(2) + ": " + rs.getString(3) + " - "
          + rs.getString(4));
      rs.last();
      System.out.println(rs.getString(2) + ": " + rs.getString(3) + " - "
          + rs.getString(4));
    } catch (SQLException ex) {
      ex.printStackTrace();
    }
  }

  public static Connection getConnection() throws SQLException {
    Connection conn = null;
    String hostname = null;
    String port = null;
    String database = null;
    String username = null;
    String password = null;
    String driver = null;
    String jdbcUrl;
    if (driver.equals("derby")) {
      jdbcUrl = "jdbc:derby://" + hostname + ":" + port + "/" + database;
    } else {
      jdbcUrl = "jdbc:oracle:thin:@" + hostname + ":" + port + ":" + database;
    }
    conn = DriverManager.getConnection(jdbcUrl, username, password);
    System.out.println("Successfully connected");
    return conn;
  }
}

ResultSet Scroll Type Constants

Constant Description
ResultSet.TYPE_FORWARD_ONLY Default type, allows forward movement only.
ResultSet.TYPE_SCROLL_INSENSITIVEAllows forward and backward movement. Not sensitive to ResultSet updates.
ResultSet.TYPE_SCROLL_SENSITIVE Allows forward and backward movement. Sensitive to ResultSet updates.

Related Tutorials