Wednesday 1 October 2014

How to retrieve data from ResultSet

Whenever you stored the results of a query in ResultSet object, the results are kept in set of rows. 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. Using next() method you can move the cursor forward one row from its current position.

/* Step 1: Import sql package */
import java.sql.*;

public class SampleApp {
    
    /* Update username, password and driver details here */
    static Connection getConnection() throws ClassNotFoundException, SQLException{
         /* Step 2: Load Driver */
        System.out.println("Loading/Registering driver");  
       
        Class.forName("com.mysql.jdbc.Driver");
         
        /* Step 3: Open connection to database */
        System.out.println("Connecting to database");
        String url = "jdbc:mysql://localhost/world";
        String userName = "root";
        String pasword = "tiger";
        return DriverManager.getConnection(url, userName, pasword);
    }
    
    public static void main(String args[]) throws SQLException, ClassNotFoundException{
        
        Connection conn = getConnection();

          /* Create table employee */
        String query = "CREATE TABLE employee (id int, name varchar(30), PRIMARY KEY(id))";
        Statement stmt = conn.createStatement();
        stmt.execute(query);     
        
        /* Insert data to employee table */
        query = "INSERT INTO employee values(1, \"Krishna\")";
        stmt.execute(query);
        query = "INSERT INTO employee values(2, \"Arjun\")";
        stmt.execute(query);        
        query = "INSERT INTO employee values(3, \"Ptr\")";
        stmt.execute(query);

        query = "SELECT * FROM employee";
        ResultSet rs = stmt.executeQuery(query);
        
        while(rs.next()){
            int id  = rs.getInt("id");
            String name = rs.getString("name");
            System.out.println(id +" " + name);
        }
        
        System.out.println("Dropping table employee");
        query = "DROP TABLE employee";
        stmt.execute(query);
        
 rs.close();
        stmt.close();
        conn.close();
    }
}

Output
Loading/Registering driver
Connecting to database
1 Krishna
2 Arjun
3 Ptr
Dropping table employee

ResultSet rs = stmt.executeQuery(query);
Above statement creates a ResultSet object.

while(rs.next()){
    int id = rs.getInt("id");
    String name = rs.getString("name");
    System.out.println(id +" " + name);
}

By using next() method, we can iterate through all the rows in the result.


Prevoius                                                 Next                                                 Home

No comments:

Post a Comment