ResultSet example

For accessing data from a table use the below steps:
  • Create a statement object.
    Statement stmt = conn.createStatement();
  • Instead of using execute update we need to use "executeQuery" method. This method returns "ResultSet" object. Using ResultSet we can fetch the data.
By using the methods ResultSet.getXXX() we can get the values of the column. At any point of time, we will be able to access only one row using the ResutlSet. In the below statement or equation a pointer is created and it points to the before first row, as shown in Fig(a).
When the result set is opened the current row will be set to before first row. To access the first row, we need to execute ResultSet.next(). "ResultSet.next()" method returns true if it is able to move to the next row and a false value if it cannot move to the next row.
package com.ram.app;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

public class ResultSetExample {
 public static void main(String[] args) throws Exception{
  Class.forName("oracle.jdbc.driver.OracleDriver");
  Connection conn = DriverManager.getConnection("dbc:oracle:thin:@localhost:1521:xe","hr","hr");
  
  Statement stmt = conn.createStatement();
  String query = "select employee_id, first_name from employees";
  ResultSet rs = stmt.executeQuery(query);
  
  while(rs.next()){
   System.out.print("Employee_Id = "+rs.getString(1));
   System.out.println("  First_Name = "+rs.getString("first_name"));
  }
  
 }
}

Execute ResultSetExample.java file. Output is given below.

No comments:

Post a Comment