Using named parameters in CALL statements in JDBC applications
The IBM® Data Server Driver for JDBC and SQLJ provides several ways to use named parameters when you call stored procedures. Named parameters use a different syntax from named parameter markers.
About this task
You can use named parameters in either or both of the following places in a JDBC application:
- In the CALL statement
With named parameters, you do not need to specify parameters in the CALL statement in the same order that they appear in the stored procedure definition. In addition, you do not need to specify all parameters in the CALL statement. Unspecified parameters take the default values that are specified in the stored procedure definition.
- In CallableStatement.setXXX, CallableStatement.getXXX,
and CallableStatement.registerOutParameter methods
You can make your programs easier to read by specifying parameter names as they appear in the stored procedure definition, rather than the positions of the parameters in the definition.
Procedure
To use named parameters with CALL statements, follow these steps:
Example
CREATE PROCEDURE SALS (
OUT retcode INTEGER,
IN lowsal DOUBLE,
IN medsal DOUBLE,
IN highsal DOUBLE DEFAULT 100000,
IN department CHAR(3) DEFAULT '---')
SPECIFIC JDBC_SALS
DYNAMIC RESULT SETS 0
DETERMINISTIC
LANGUAGE JAVA
PARAMETER STYLE JAVA
NO DBINFO
FENCED
THREADSAFE
MODIFIES SQL DATA
PROGRAM TYPE SUB
EXTERNAL NAME 'MYJAR:MyClass.sals'
The input parameters in the CALL statement are represented
by named parameters. The third and fourth parameters are called with
the default values for the stored procedure. The numbers to the right
of selected statements correspond to the previously-described steps.int hvRetCode; // Host variable for output parameter
Connection con;
CallableStatement cstmt;
ResultSet rs;
…
cstmt = con.prepareCall(
"CALL SALS(retcode=>?,lowsal=>?,medsal=>?,highsal=>DEFAULT)"); 1
// Prepare the Call statement.
// Implicitly use the default
// value for the last parameter
// by omitting it.
cstmt.setDouble ("lowsal", 10000); 2
cstmt.setDouble ("medsal", 50000);
cstmt.registerOutParameter ("retcode", Types.INTEGER); 3
// Register output parameter
cstmt.executeUpdate(); // Call the stored procedure 4
hvRetCode = cstmt.getInt("retcode"); 6
System.out.println("Return code from SALS call: " + hvRetCode);
cstmt.close(); 7