Program to use TYPE_FORWARD_ONLY ResultSet type 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 how to use TYPE_FORWARD_ONLY ResultSet type in java


--Before executing java program execute these database scripts  >
create table EMPLOYEE(ID number(4),NAME varchar2(22));
insert into EMPLOYEE values(1, 'ankit');
insert into EMPLOYEE values(2, 'rohit');
insert into EMPLOYEE values(3, 'amy');
commit;

--If table already exists then execute the DROP command >
drop table EMPLOYEE;


EMPLOYEE table will look like this >

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 TYPE_FORWARD_ONLY_ResultSetType {
   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!");
                
                 //ResultSet type = TYPE_FORWARD_ONLY
                 prepStmt = con.prepareStatement("select NAME from EMPLOYEE",
                              ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE);
                
                 rs = prepStmt.executeQuery();
                 while (rs.next()) {
                       System.out.println(rs.getString("NAME"));
                 }
                
                 System.out.println("\nTYPE_FORWARD_ONLY - "+rs.getType()); //1003 is TYPE_FORWARD_ONLY
                
          } 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();
                 }
          }
   }
}
/*OUTPUT
Connection established successfully!
ankit
rohit
amy
TYPE_FORWARD_ONLY - 1003
*/
//Note : TYPE_FORWARD_ONLY is the default ResultSet type in java, but program shows how to declare it in program
                

Labels: Core Java JDBC
eEdit
Must read for you :