How to handle ResultSet?

Data in a ResultSet is logically organized into a virtual table consisting of rows and columns. The ResultSet uses a virtual cursor to point to a row in the virtual table.
•The ResultSet executeQuery(String) method of Statement class executes SQL statement and returns rows (result set) retrieved from the database table.
•The int executeUpdate(String) method of Statement class executes SQL DML and DDL statement passed as argument to method and return an integer that represent no of rows affected.
•In case of Result set we can move to next row using boolean next() method of ResultSet class.
Accessing Columns
•Any particular field (column) value of row in result set is accessed by using the XXX getXXX() methods of ResultSet class.
•The getXXX() method take two types of arguments as
getXXX(String) : column name as argument
getXXX(int) : column index as argument as per sequence of the column selected in select statement.
• The methods are as:
String getString(int)
boolean getBoolean(int)
int getInt(int)
float getFloat(int)
java.sql.Date getDate(int)
•A method boolean next() checks the availability of rows and makes the next rows as current row to access the information from it.
Example:
import java.sql.*;
class demo
{
public static void main(String[] args){
Connection con=null;
Statement stmt=null;
ResultSet rs=null;
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE","system","oracle");
stmt=con.createStatement();
rs=stmt.executeQuery("select * from emp");
while(rs.next()){
System.out.println(rs.getString(1)+"\t"+rs.getString(2)+"\t"+rs.getString(3));
}}catch(Exception e){
System.out.println("the exception is::::->"+e);
}
finally{
try{
rs.close();
stmt.close();
con.close();}
catch(Exception e){
System.out.println("2nd try block exception:::->"+e);
}}}};

No comments:

Post a Comment