What is meant by ResultSet object and How to Fetch the Data from - TopicsExpress



          

What is meant by ResultSet object and How to Fetch the Data from Database? Ans: In Jdbc applications if we use Selection group SQL Query as parameter to executeQuery() method then JVM will send that selection group SQL Query to the Database Engine,where Database Engine will execute that SQL Query,fetch the data from Database and send back to Java application. --->At Java Application the fetched data will be stored in the form of an object at heap memory called as ResultSet. -->As per the predefined implementation of executeQuery method JVM will return the generated ResultSet object reference as return value. ReslutSet rs=st.executeQuery(select * from emp1); -->When ResultSet object is created automatically a cursor will be created positioned before the first record. -->If we want to read the records data from resultset object the for each and every record we have to check whether the next record is available or not from resultset cursor position, if it is available then we have to move resultset cursor to the next record position. -->To perform the above work we have to use the following method from resultset public boolean next() -->After getting ResultsSet cursor to a particular Record position we have to retrieve the data from respective columns,for this we have to use the following overloaded method public xxx getxxx(int field_No) public xxx getxxx(String field_Name) where xxx may be byte,short,int..... Ex: while(rs.next()) { System.out.println(rs.getInt(1)); System.out.println(rs.getString(2)); System.out.println(rs.getFloat(3)); } The following example demonstrate how to fetch the data from database through ResultSet object: ================================================= import java.sql.*; import oracle.jdbc.driver.*; class DBL { Connection con; Statement st; ResultSet rs; public DBL() { try{ Class.forName(oracle.jdbc.driver.OracleDriver); con=DriverManager.getConnection(jdbc:oracle:thin:@localhost:1521:xe,system,durga); st=con.createStatement(); } catch(Exception e) { e.printStackTrace(); } } public void fetch() { try { rs=st.executeQuery(select * from emp1); System.out.println(ENO ENAME ESAL); while(rs.next()) { System.out.println(rs.getInt(1)++rs.getString(2)++rs.getFloat(3)); } } catch(Exception e){ e.printStackTrace(); } finally { try { con.close(); } catch(Exception e) { e.printStackTrace(); } } } } class ResultSetEx1 { public static void main(String args[]) { DBL d=new DBL(); d.fetch(); } }
Posted on: Sat, 13 Dec 2014 14:08:43 +0000

© 2015