Java Reference
In-Depth Information
Prepared Statements
A prepared statement is an SQL statement that contains parameters, and the
java.sql.PreparedStatement interface is used to represent a prepared SQL state-
ment. Before a prepared statement can be executed, each parameter needs to
be assigned using one of the set methods in the PreparedStatement interface.
A question mark is used to denote a parameter.
For example, the following prepared statement inserts a new row in a table
called Employees:
INSERT INTO Employees VALUES (?, ?, ?, ?)
This prepared statement contains four parameters. When the Prepared-
Statement object is created using the Connection object, this statement is sent
to the database and precompiled, allowing the database to execute the state-
ment at a faster rate.
Prepared statements are preferred over simple statements for two good
reasons:
Prepared statements execute faster because they are precompiled.
■■
As you soon may discover, prepared statements are easier to code
because you do not have to worry about things like single quotes
around text or missing commas.
■■
My second point is demonstrated in the addMovie() method of the
MovieDatabase class, which contains a simple but still tedious SQL
statement.
Using a prepared statement involves the following steps:
1.
Create a PreparedStatement object using one of the prepareStatement()
methods of the connection.
2.
Use the appropriate set methods of the PreparedStatement interface to
set each of the parameters of the prepared statement.
3.
Invoke one of the execute() methods of the PreparedStatement interface
to execute the statement.
Step 1: Preparing the Statement
Let's start with the Connection interface, which contains the following six
methods for creating a PreparedStatement:
Search WWH ::




Custom Search