Monday, January 19, 2009

7.1.2 Passing IN Parameters

Before a PreparedStatement object is executed, the value of each ? parameter must be set. This is done by calling the setter method (setInt, setString, and so on), that is appropriate for the parameter type. For example, if the parameter is of type long in the Java programming language, the method to use is setLong. The first argument to the setter methods is the ordinal position of the parameter to be set, with numbering starting at 1. The second argument is the value to which the parameter is to be set. For example, the following code sets the first parameter to 123456789 and the second parameter to 100000000:
pstmt.setLong(1, 123456789);
pstmt.setLong(2, 100000000);
Once a parameter value has been set for a given statement, it can be used for multiple executions of that statement until it is cleared by a call to the method clearParameters or until a new value is set.
When a connection has its auto-commit mode enabled, each statement is committed automatically when it is completed. Some database systems do not retain prepared statements across commits, so for them, the driver will have to recompile the prepared statement after each commit. This means that for these DBMSs, it may actually be less efficient to use a PreparedStatement object in place of a Statement object that is executed many times.

Using pstmt, the PreparedStatement object created above, the following code illustrates setting values for the two parameter placeholders and executing pstmt 10 times. In this example, the first parameter is set to "Hi" and remains constant. The second parameter is set to a different value each time around the for loop, starting with 0 and ending with 9.
pstmt.setString(1, "Hi");
for (int i = 0; i < 10; i++) {
pstmt.setInt(2, i);
int rowCount = pstmt.executeUpdate();
}
Features introduced in the JDBC 2.0 API made it possible to set a parameter placeholder with an SQL99 data type, as shown in the following example, where statistics is a Blob object representing an SQL BLOB value, and departments is an Array object representing an SQL ARRAY value.

PreparedStatement pstmt = con.prepareStatement(
"UPDATE Table3 SET Stats = ? WHERE Depts = ?");
pstmt.setBlob(1, statistics);
pstmt.setArray(2, departments);

0 Comments: