Monday, January 19, 2009

8.1.6 INOUT Parameters

A parameter that supplies input as well as accepts output (an INOUT parameter) requires a call to the appropriate setter method (inherited from PreparedStatement) in addition to a call to the method registerOutParameter. The setter method sets a parameter's value as an input parameter, and the method registerOutParameter registers its JDBC type as an output parameter. The setter method provides a Java value that the driver converts to a JDBC value before sending it to the database. The JDBC type of this IN value and the JDBC type supplied to the method registerOutParameter should be the same. Then, to retrieve the output value, a corresponding getter method is used. For example, a parameter whose Java type is byte should use the method setByte to assign the input value, should supply a TINYINT as the JDBC type to registerOutParameter, and should use getByte to retrieve the output value. ("Mapping SQL and Java Types" on page 107 contains tables of type mappings.)
The following example assumes that there is a stored procedure reviseTotal whose only parameter is an INOUT parameter. The method setByte sets the parameter to 25, which the driver will send to the database as a JDBC TINYINT. Next registerOutParameter registers the parameter as a JDBC TINYINT. After the stored procedure is executed, a new JDBC TINYINT value is returned, and the method getByte will retrieve this new value as a Java byte. Since the stored procedure called in this example returns an update count, the method executeUpdate is used.

CallableStatement cstmt = con.prepareCall("{call reviseTotal(?)}");
cstmt.setByte(1, (byte)25);
cstmt.registerOutParameter(1, java.sql.Types.TINYINT);
cstmt.executeUpdate();
byte x = cstmt.getByte(1);

0 Comments: