JDBC ResultSet Example


 

JDBC ResultSet Example

In this example, we are discuss about ResultSet class that provides methods for access (retrieving, navigating, and manipulating) database query results

In this example, we are discuss about ResultSet class that provides methods for access (retrieving, navigating, and manipulating) database query results

JDBC ResultSet Example:

In this example, we are discuss about ResultSet class that provides methods for access (retrieving, navigating, and manipulating) database query results. Through this example you can see how to use ResultSet in the application for accessing data.

First we will create a java class that will have database connectivity after that we will create a Statement object and SQL select statement for retrieving data form the database as:

Statement stmt = connection.createStatement();

String selectquery = "select * from user";

After that we will execute this statement on the created statement object and store the result in the resultset object  as:

ResultSet rs = stmt.executeQuery(selectquery); 

Now we will access data using resultset methods.

The full code of the example is:

package ResultSet;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class ResultSetExample {

  public static void main(String[] args) {
    Connection connection = null;
      String url = "jdbc:mysql://localhost:3306/";
      String dbName = "roseindia_jdbc_tutorials";
      String driverName = "com.mysql.jdbc.Driver";
      String userName = "root";
      String password = "root";
      try{
        Class.forName(driverName).newInstance();
        connection = DriverManager.getConnection(url+dbName, userName, password);
        try{
          Statement stmt = connection.createStatement();
          String selectquery = "select * from user";
          ResultSet rs = stmt.executeQuery(selectquery);
          while(rs.next()){
            System.out.print("User ID :" + rs.getInt(1)" ");
              System.out.println("User Name :" + rs.getString(2));
          }
        }
        catch(SQLException s){
          System.out.println(s);
        }
        connection.close();
      }
      catch (Exception e){
        e.printStackTrace();
      }
  }
}

In this example we have used resultset next() method to retrieve data. Now we will run this example using eclipse IDE and see the result.

Program output:

The database table output is:

And the eclipse console output is:

Download source code

Ads