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-

<br />
/****************************************************************************************<br />
 * Created on 05-2011 Copyright(c) http://kodehelp.com All Rights Reserved.<br />
 ****************************************************************************************/<br />
package com.kodehelp.javasql;</p>
<p>import java.sql.*;</p>
<p>/**<br />
 * Created by http://kodehelp.com<br />
 * Date: 5/9/11<br />
 */<br />
public class GetValueFromResultset {<br />
     public static void main(String[] args) throws SQLException, ClassNotFoundException {<br />
        final String driver = "oracle.jdbc.driver.OracleDriver";<br />
        final String url = "jdbc:oracle:thin:@HOST:PORT:SID";<br />
        final String USERNAME = "USERNAME";<br />
        final String PASSWORD = "PASSWORD";<br />
        Connection conn = null;<br />
        try{<br />
          Class.forName(driver); // load Oracle driver<br />
          conn = DriverManager.getConnection(url, USERNAME, PASSWORD);<br />
          String query = "SELECT Id, Name, Dept FROM Employee";<br />
          PreparedStatement ps = conn.prepareStatement(query);<br />
          ResultSet rs = ps.executeQuery();<br />
          while (rs.next()) {<br />
            // Read values using column name<br />
            String id = rs.getString("Id");<br />
            String Name = rs.getString("Name");<br />
            // Read values using column index<br />
            String dept = rs.getString(3);</p>
<p>            System.out.println("ID:"+id+" Name:"+Name+" Dept:"+dept);<br />
          }<br />
        }catch (ClassNotFoundException cnfEx){<br />
            throw cnfEx;<br />
        }catch (SQLException sqlEx){<br />
            throw sqlEx;<br />
        }finally{<br />
            if(conn!=null){<br />
                conn.close();<br />
            }<br />
        }<br />
    }<br />
}<br />