Monday, January 19, 2009

8.1.4 OUT Parameters

If the stored procedure returns OUT parameters, the JDBC type of each OUT parameter must be registered before the CallableStatement object can be executed. This is necessary because some DBMSs require the SQL type (which the JDBC type represents), not because the JDBC API requires it. JDBC types, a set of generic SQL type identifiers that represent the most commonly used SQL types, are explained fully in the chapter "Mapping SQL and Java Types" on page 107.
Registering the JDBC type is done with the method registerOutParameter. Then after the statement has been executed, CallableStatement's getter methods can be used to retrieve OUT parameter values. The correct CallableStatement.getter method to use is the type in the Java programming language that corresponds to the JDBC type registered for that parameter. (The standard mapping from JDBC types to Java types is shown in Table 9.1 on page 128.) In other words, registerOutParameter uses JDBC types (so that tjey match the data type that the database will return), and the getter mathods cast this to a Java type.

To illustrate, the following code registers the OUT parameters, executes the stored procedure called by cstmt, and then retrieves the values returned in the OUT parameters. The method getByte retrieves a Java byte from the first OUT parameter, and getBigDecimal retrieves a java.math.BigDecimal object from the second OUT parameter. The method executeQuery is used to execute cstmt because the stored procedure that it calls returns a result set.

CallableStatement cstmt = con.prepareCall(
"{call getTestData(?, ?)}");
cstmt.registerOutParameter(1, java.sql.Types.TINYINT);
cstmt.registerOutParameter(2, java.sql.Types.DECIMAL);
ResultSet rs = cstmt.executeQuery();
// . . . retrieve result set values with rs.getter methods
byte x = cstmt.getByte(1);
java.math.BigDecimal n = cstmt.getBigDecimal(2);

Unlike ResultSet, CallableStatement does not provide a special mechanism for retrieving large OUT values incrementally. More specifically, it does not have getter methods for streams of data, such as getAsciiStream or getBinary-Stream. However, the JDBC 2.0 API provides CallableStatement methods for retrieving SQL3 datatypes as OUT or INOUT parameters, which includes the methods getBlob and getClob for retrieving binary large objects and character large objects.

0 Comments: