Prepared Statements
The
PreparedStatement
object is a close relative of
the Statement
object. Both accomplish roughly the
same thing: running SQL statements.
PreparedStatement
, however, allows you to
precompile your SQL and run it repeatedly, adjusting specific
parameters as necessary. Since processing SQL strings is a large part
of a database’s overhead, getting compilation out of
the way at the start can significantly improve performance. With
proper use, it can also simplify otherwise tedious database tasks.
As with
Statement
, you create a
PreparedStatement
object from a
Connection
object. In this case, though, the SQL
is specified at creation instead of execution, using the
prepareStatement( )
method of
Connection
:
PreparedStatement pstmt = con.prepareStatement( "INSERT INTO EMPLOYEES (NAME, PHONE) VALUES (?, ?)");
This SQL statement inserts
a new row into the EMPLOYEES
table, setting the
NAME
and PHONE
columns to
certain values. Since the whole point of a
PreparedStatement
is to be able to execute the
statement repeatedly, we don’t specify values in the
call to prepareStatement( )
, but instead use
question marks (?
) to indicate parameters for the
statement. To actually run the statement, we specify values for the
parameters and then execute the statement:
pstmt.clearParameters( ); pstmt.setString(1, "Jimmy Adelphi"); pstmt.setString(2, "201 555-7823"); pstmt.executeUpdate( );
Before setting parameters, we clear
out any previously specified parameters with the
clearParameters( ...
Get Java Enterprise in a Nutshell, Second Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.