ResultSet Example

A result set contains the results of a SQL query. The results are kept in a set of rows, one of which is designated the current row. A row must be made current before data can be retrieved from it. The result set maintains a reference to the current row called the cursor.
The cursor is positioned before the first row when a result set is created. When a result set's next() method is called, the cursor moves to the first row of the result set and that row becomes the current row.
There are two ways to retrieve the data from the current row. 


1) column index :  
Example : String s = rs.getString(1);
     
2) column name. 
Example : s = rs.getString("col_string"
);



Example Using ResultSet :


package com.JavaStuff.jdbc;

import java.sql.*;
/**
 * @author JavaStuff
 */
public class ResultSetExample {

public static void main(String args[])throws 
SQLException, ClassNotFoundException {

//Get Connection
Connection con=prepareConnection (); 

// Obtain a Statement
Statement st=con.createStatement ();
String query = "select * from mytable";
//Execute the Query
ResultSet rs=st.executeQuery (query);
System.out.println ("COL1\tCOL2\tCOL3");
                while (rs.next ()){
System.out.print (rs.getString ("COL1") + "\t");
System.out.print (rs.getInt ("COL2") + "\t");
System.out.println (rs.getDouble ("COL3"));
}//while
con.close ();
}//main

public static Connection prepareConnection()
throws SQLException,
  ClassNotFoundException {

String driverClassName="oracle.jdbc.driver.OracleDriver";
String url="jdbc:oracle:thin:@mysys:1521:Javastuff";
String username="scott";
String password="tiger";
//Load driver class
Class.forName (driverClassName);

// Obtain a connection
return DriverManager. getConnection (url, username, password);
}//prepareConnection
}//class



Note : To execute the following example you can replace username and password with your actual user name and password.



Enter your email address to get our daily JOBS & INTERVIEW FAQ's Straight to your Inbox.

Make sure to activate your subscription by clicking on the activation link sent to your email