Hitachi

Hitachi Advanced Database Application Development Guide


7.4.2 How to use dynamic parameters

The procedure for using dynamic parameters to retrieve data is as follows:

Organization of this subsection

(1) Generating a PreparedStatement object

Generate a PreparedStatement object, and then send the SELECT statement with the dynamic parameters specified to the HADB server.

If a connection to the HADB server has already been established, you can use the prepareStatement method of the Connection object to generate a PreparedStatement object.

The following example generates a PreparedStatement object:

 // Connect to the HADB server
 Connection con = DriverManager.getConnection(url, info);
 
 // Generate a PreparedStatement object
 PreparedStatement pstmt =
 con.prepareStatement("SELECT * FROM \"SAMPLE\" WHERE \"CODE\" = ? AND \"STATE\" = ?");

If the SELECT statement is specified in the argument of the prepareStatement method, the SELECT statement is preprocessed and a PreparedStatement object is generated.

To specify dynamic parameters in an SQL statement, values must have been set for all the specified dynamic parameters before the SQL statement is executed. You use a setXXX method to set a value in a dynamic parameter.

(2) Executing the SELECT statement

Use the executeQuery method with no argument specified to execute the SELECT statement. The following example executes a SELECT statement that uses dynamic parameters:

 PreparedStatement pstmt =
 con.prepareStatement("SELECT * FROM \"SAMPLE\" WHERE \"CODE\" = ? AND \"STATE\" = ?");
 
 // Set a value in the first dynamic parameter
 pstmt.setInt(1, 12345);
 // Set a value in the second dynamic
 pstmt.setString(2, "Boston");
 
 // Execute a preprocessed SQL statement to obtain the ResultSet object
 ResultSet rs = pstmt.executeQuery();

When the SELECT statement is executed, the retrieval results are stored in a ResultSet object.

(3) Getting the retrieval results

For details about how to get the retrieval results, see (3) Getting the retrieval results in 7.4.1 How to retrieve data.