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.