How to retrieve/get values from ResultSet in Java?

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

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

import java.sql.*;

/**
* Created by https://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();
}
}
}
}
[/java]

Please Post Your Comments & Reviews

Your email address will not be published. Required fields are marked *