Monday, January 19, 2009

7.1.1 Creating PreparedStatement Objects

The following code fragment, where con is a Connection object, creates a PreparedStatement object containing an SQL update statement with two placeholders for IN parameters:
PreparedStatement pstmt = con.prepareStatement(

"UPDATE table4 SET m = ? WHERE x = ?");

The object pstmt now contains the statement "UPDATE table4 SET m = ? WHERE x = ?", which has already been sent to the DBMS and been prepared for execution.
As with Statement objects, it is possible to create a PreparedStatement object that contains a query rather than an update statement; in fact, this is often done to improve efficiency for SQL statements that are executed many times. Using the new version of the method prepareStatement included in the JDBC 2.0 core API, the PreparedStatement object can produce ResultSet objects that are scrollable and updatable. For example, the following code fragment creates a PreparedStatement object such that each time it is executed, it will produce a ResultSet object that is scrollable and updatable.

PreparedStatement pstmt2 = con.prepareStatement(
"SELECT a, b, c FROM Table1", ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
ResultSet rs = pstmt2.executeQuery();

The object that rs represents is a result set with all the values stored in columns a, b, and c of Table1, and rs is scrollable and can be updated. Each time pstmt2 is executed, it will produce a result set that is scrollable and updatable.
Normally ResultSet objects are closed when the transaction in which they were created is closed. The JDBC 3.0 API makes it possible to hold a result set (cursor) open when the transaction is committed, which may sometimes be the desired behavior. Adding the ResultSet constant HOLD_CURSORS_OVER_COMMIT to the other constants passed to the prepareStatement method will create a PreparedStatement object that produces ResultSet objects that stay open rather than being closed when the transaction is committed. For example, if ResultSet.HOLD_CURSORS_OVER_COMMIT were added as the last argument to the prepareStatement method in the preceding code fragment, rs would be held open when the transaction in which it was created was committed. In fact, rs would stay open until it was explicitly closed.

0 Comments: