Thursday 21 February 2013

How ResultSet fetches data from database

ResultSet is set of rows from a database. When any statement object fires a query on database then output is stored in ResultSet object.
ResultSet access the results through a cursor and cursor moves row by row. It fetches one row at a time.
For Example:
We have a table named emp_info contains 4 column's 
"emp_id"  "emp_fname"  "emp_lname"  "emp_dob"
with 5 employees entries.

Code:
Connection conn=null;
Statement stmnt = null;
ResultSet rs = null;
try
{
   // Create the Statement
   stmnt = conn.createStatement();

   // Execute the query to obtain the ResultSet 
   rs = stmnt.executeQuery("select * from emp_info");
  
   // Fetches rows one by one
   // Loop executes five times because table contain record for five employees
   while(rs.next())
   {
      System.out.println("Emp ID: " + rs.getString("emp_id")); 
      System.out.println("First name: " + rs.getString("emp_fname"));
      System.out.println("Last name: " + rs.getString("emp_lname"));
      System.out.println("Date Of Birth: " + rs.getDate("emp_dob"));  
}
catch(Exception ex)
{
   System.err.println("Database exception: " + ex);
} 

rs.next() places the cursor on starting point of records and when next time it will execute, point the starting position of next record.
We can use columns number at the place of columns  name (rs.getString("emp_id"); => rs.getString(1);). Remember columns index started from 1.

Difference Between Prepared and PreparedStatement

Four Necessary steps to complete execution of a query:
                                1. Parse the incoming SQL Query
                                2. Compile the SQL Query
                                3. Plan/optimize the data acquisition path
                                4. Execute the optimized query / acquire and return data


A Statement will need to perform four steps above for each SQL query. A PreparedStatement pre-executes steps (1) - (3) in the execution process above. Thus, when creating a PreparedStatement some pre-optimization is performed immediately. The effect is to lessen the load on the database engine at execution time.

Another advantage of the PreparedStatement class is the ability to create an incomplete query and supply parameter values at execution time.
Query like this:-
"SELECT firstName FROM employees WHERE salary > ?");

after prepare a statement object we can set the values for incomplete places.
like this:-  stmnt.setInt(1, 200);

There are three different kinds of statements:
  • Statement: Used to implement simple SQL statements with no parameters.
  • PreparedStatement: Used for precompiling SQL statements that might contain input parameters.
  • CallableStatement: Used to execute stored procedures that may contain both input and output parameters.
 Statement Example:

Connection conn=null;
Statement stmnt = null;
ResultSet rs = null;
try
{
   // Create the Statement
   stmnt = conn.createStatement();

   // Execute the query to obtain the ResultSet 
   rs = stmnt.executeQuery("select * from aTable");
}
catch(Exception ex)
{

   System.err.println("Database exception: " + ex);
} 

PreparedStatement Example:

Connection conn=null;
PreparedStatement stmnt = null;
ResultSet rs = null;
try
{
   // Create the PreparedStatement 
   // Step 1-3 performed at here 
   stmnt = conn.prepareStatement("select * from aTable");

   // Execute the query to obtain the ResultSet 
   rs = stmnt.executeQuery();
}
catch(Exception ex)
{
   System.err.println("Database exception: " + ex);
} 


Parametrized PreparedStatement Example:

// Assume a database connection, conn.
PreparedStatement stmnt = null;
ResultSet rs = null;
try
{
  // Create the PreparedStatement, leaving a '?'
  // to indicate placement of a parameter.
  stmnt = conn.prepareStatement(
    "SELECT firstName FROM employees WHERE salary > ?");

  // Complete the statement 
  // Set 200 at the place of '?'
  stmnt.setInt(1, 200);

  // Execute the query to obtain the ResultSet 
  rs = stmnt.executeQuery();
}
  catch(Exception ex)
{
  System.err.println("Database exception: " + ex);
}