Program to use CLOSE_CURSORS_AT_COMMIT ResultSet holdability in java


Before reading this article I’ll recommend you to read : JDBC - What is ResultSet in java - Types, concurrency, holdability of ResultSet in java
Program to demonstrate use of CLOSE_CURSORS_AT_COMMIT ResultSet holdability in java

CLOSE_CURSORS_AT_COMMIT -  CLOSE_CURSORS_AT_COMMIT holdability indicates that open ResultSet objects will be closed when the current transaction is committed.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */
public class CLOSE_CURSORS_AT_COMMIT_ResultSetHoldability {
   public static void main(String... arg) {
          Connection con = null;
          PreparedStatement prepStmt = null;
          ResultSet rs = null;                 
          try {
                 // registering Oracle driver class
                 Class.forName("oracle.jdbc.driver.OracleDriver");
                 // getting connection
                 con = DriverManager.getConnection(
                              "jdbc:oracle:thin:@localhost:1521:orcl",
                              "ankit", "Oracle123");
                 System.out.println("Connection established successfully!");
                
                 //Begin Transaction T1
                 con.setAutoCommit(false);
                
                 //ResultSet holdability = CLOSE_CURSORS_AT_COMMIT
                 prepStmt = con.prepareStatement("select NAME from EMPLOYEE",
                              ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE,
                                ResultSet.CLOSE_CURSORS_AT_COMMIT);
                
                 rs = prepStmt.executeQuery();
                
                 // LOGIC........................
                
                 //Commit Transaction T1
                 con.commit();
                 //CLOSE_CURSORS_AT_COMMIT holdability indicates that open ResultSet
                 //objects will be closed when the current transaction is committed.
                
          } catch (ClassNotFoundException e) {
                 e.printStackTrace();
          } catch (SQLException e) {
                 e.printStackTrace();
          }
          finally{
                 try {
                       if(rs!=null) rs.close(); //close resultSet
                       if(prepStmt!=null) prepStmt.close(); //close PreparedStatement
                       if(con!=null) con.close(); // close connection
                 } catch (SQLException e) {
                       e.printStackTrace();
                 }
          }
   }
}

Labels: Core Java JDBC
eEdit
Must read for you :