Java JDBC How to - Get to know the Behaviour of ResultSet.TYPE_SCROLL_SENSITIVE








Question

We would like to know how to get to know the Behaviour of ResultSet.TYPE_SCROLL_SENSITIVE.

Answer

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
//from   www  .  j av  a2  s. c o  m
public class Main {
  public static void main(String[] args) throws SQLException {
    // DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
    Connection conn = DriverManager.getConnection("jdbc:oracle:oci8:@yourDB",
        "scott", "tiger");

    Statement stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
        ResultSet.CONCUR_UPDATABLE);

    stmt.setFetchSize(1);
    ResultSet rset = stmt.executeQuery("select EMPNO, ENAME, SAL from EMP");
    showProperty(rset);

    while (rset.next()) {
      System.out.println(rset.getInt(1) + " " + rset.getString(2) + " "
          + rset.getInt(3));
    }
    doSomeChanges(conn);
    // Place the cursor before the first row
    rset.beforeFirst();

    while (rset.next()) {
      System.out.println(rset.getInt(1) + " " + rset.getString(2) + " "
          + rset.getInt(3));
    }
    rset.close();
    stmt.close();
    cleanup(conn);
    conn.close();
  }

  public static void doSomeChanges(Connection conn) throws SQLException {
    Statement otherStmt = conn.createStatement();
    otherStmt.execute("update emp set sal = sal + 500");
    otherStmt.execute("commit");
    otherStmt.close();
  }

  public static void showProperty(ResultSet rset) throws SQLException {
    switch (rset.getType()) {
    case ResultSet.TYPE_FORWARD_ONLY:
      System.out.println("Result set type: TYPE_FORWARD_ONLY");
      break;
    case ResultSet.TYPE_SCROLL_INSENSITIVE:
      System.out.println("Result set type: TYPE_SCROLL_INSENSITIVE");
      break;
    case ResultSet.TYPE_SCROLL_SENSITIVE:
      System.out.println("Result set type: TYPE_SCROLL_SENSITIVE");
      break;
    default:
      System.out.println("Invalid type");
      break;
    }
    switch (rset.getConcurrency()) {
    case ResultSet.CONCUR_UPDATABLE:
      System.out.println("Result set concurrency: ResultSet.CONCUR_UPDATABLE");
      break;
    case ResultSet.CONCUR_READ_ONLY:
      System.out.println("Result set concurrency: ResultSet.CONCUR_READ_ONLY");
      break;
    default:
      System.out.println("Invalid type");
      break;
    }
    System.out.println("fetch size: " + rset.getFetchSize());
  }

  public static void cleanup(Connection conn) throws SQLException {
    Statement stmt = conn.createStatement();
    stmt.execute("UPDATE EMP SET SAL = SAL - 500");
    stmt.execute("COMMIT");
    stmt.close();
  }
}