JDBC Tutorials - Herong's Tutorial Notes
Dr. Herong Yang, Version 2.11

Capturing ResultSet with executeQuery()

This section describes how to capture ResultSet objects by calling executeQuery() to execute the CALL statement.

There two ways to execute the CALL statement enclosed in the CallableStatement object:

  • rs.executeUpdate() - Execute the CALL statement without collecting any returning ResultSet. Use this method when the stored procedure is not returning any result sets or you want to ignore them.
  • res = rs.executQuery() - Execute the CALL statement and collect the returning ResultSet objects. Use this method when the stored procedure is returning result sets and you are want to collect them.

Here is a sample program that show you how to collect the returning ResultSet of the HelloWorld() procedure:

/**
 * MySqlCallExecuteQuery.java
 * Copyright (c) 2007 by Dr. Herong Yang. All rights reserved.
 */
import java.sql.*;
public class MySqlCallExecuteQuery {
  public static void main(String [] args) {
    Connection con = null;
    try {
      com.mysql.jdbc.jdbc2.optional.MysqlDataSource ds 
        = new com.mysql.jdbc.jdbc2.optional.MysqlDataSource();
      ds.setServerName("localhost");
      ds.setPortNumber(3306);
      ds.setDatabaseName("HerongDB");
      ds.setUser("Herong");
      ds.setPassword("TopSecret");
      con = ds.getConnection();

// Create CallableStatement
      CallableStatement cs = con.prepareCall("CALL HelloWorld()");

// Execute the call statement and collect the ResultSet
      ResultSet res = cs.executeQuery();

// Retrieving the result
      res.next();
      System.out.println("Result: "+res.getString("Message"));

// Close resource
      cs.close();

      con.close();
    } catch (Exception e) {
      System.err.println("Exception: "+e.getMessage());
      e.printStackTrace();
    }
  }
}

This time the result of the query "SELECT 'Hello world!' AS Message;" in HelloWorld() procedure was successfully collected:

C:\>javac -cp .;\local\lib\mysql-connector-java-5.0.7-bin.jar 
  MySqlCallExecuteQuery.java

C:\>java -cp .;\local\lib\mysql-connector-java-5.0.7-bin.jar
  MySqlCallExecuteQuery

Result: Hello world!

Sections in This Chapter

Overview of CallableStatement Objects

"CREATE PROCEDURE" - Creating a Simple Procedure

Creating Procedures with IN and OUT Parameters

Creating Procedures with INOUT Parameters

Creating Procedures with Multiple Queries

Creating CallableStatement Objects with prepareCall()

Capturing ResultSet with executeQuery()

Creating CallableStatement Objects with Parameters

Common Errors with CallableStatement Parameters

Creating CallableStatement Objects with INOUT Parameters

Retrieving Multiple ResultSet Objects

Executing Stored Procedures without Permission

getProcedures() - Listing Stored Procedures

Dr. Herong Yang, updated in 2007
Capturing ResultSet with executeQuery()