How to retrieve/get values from ResultSet in Java?

DeeKay May 9, 2011 at 5:49 pm · java.sql

Below java code shows how to get or retrieve column values from Resultset-

/****************************************************************************************
 * Created on 05-2011 Copyright(c) http://kodehelp.com All Rights Reserved.
 ****************************************************************************************/
package com.kodehelp.javasql;

import java.sql.*;

/**
 * Created by http://kodehelp.com
 * Date: 5/9/11
 */
public class GetValueFromResultset {
     public static void main(String[] args) throws SQLException, ClassNotFoundException {
        final String driver = "oracle.jdbc.driver.OracleDriver";
        final String url = "jdbc:oracle:thin:@HOST:PORT:SID";
        final String USERNAME = "USERNAME";
        final String PASSWORD = "PASSWORD";
        Connection conn = null;
        try{
          Class.forName(driver); // load Oracle driver
          conn = DriverManager.getConnection(url, USERNAME, PASSWORD);
          String query = "SELECT Id, Name, Dept FROM Employee";
          PreparedStatement ps = conn.prepareStatement(query);
          ResultSet rs = ps.executeQuery();
          while (rs.next()) {
            // Read values using column name
            String id = rs.getString("Id");
            String Name = rs.getString("Name");
            // Read values using column index
            String dept = rs.getString(3);

            System.out.println("ID:"+id+" Name:"+Name+" Dept:"+dept);
          }
        }catch (ClassNotFoundException cnfEx){
            throw cnfEx;
        }catch (SQLException sqlEx){
            throw sqlEx;
        }finally{
            if(conn!=null){
                conn.close();
            }
        }
    }
}