Monday, January 19, 2009

8.1.1 Creating a CallableStatement Object

CallableStatement objects are created with the Connection method prepareCall. The following example, in which con is an active JDBC Connection object, creates an instance of CallableStatement.

CallableStatement cstmt = con.prepareCall(
"{call getTestData(?, ?)}");

The variable cstmt contains a call to the stored procedure getTestData, which has two input parameters and no result parameter. Whether the ? placeholders are IN, OUT, or INOUT parameters depends on the stored procedure getTestData. This instance of a CallableStatement object was created using JDBC 1.0 API; consequently, any query in the stored procedure called by cstmt will produce a default ResultSet object (one that is non-scrollable and non-updatable).
The JDBC 2.0 API provided the means to create CallableStatement objects that can produce ResultSet objects that are scrollable and updatable, as the following code fragment demonstrates.

String sql = "{call getTestData(?, ?)}";
CallableStatement cstmt2 = con.prepareCall(sql,
ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);

The variable cstmt2 contains the same call to the stored procedure TestData that cstmt does, but with cstmt2, any resultSet objects that TestData produces can be updated and are scrollable (though they will not be sensitive to updates made while they are open).
The following code fragment uses a ResultSet constant added in the JDBC 3.0 API to create a CallableStatement object that has the same characteristics as cstmt2 from the previous example, except that it will produce ResultSet objects that remain open when a transaction is committed rather than being automatically closed.

String sql = "{call getTestData(?, ?)}";
CallableStatement cstmt3 = con.prepareCall(sql,
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE),
ResultSet.HOLD_CURSORS_OVER_COMMIT);

Explanations for the constants used to indicate scrollability, updatability, and holdability are given in the chapter "ResultSet."

0 Comments: