Java Reference
In-Depth Information
Each question mark in a prepared statement denotes a parameter. The
order in which the parameters appear determines their index, with the
first parameter being index 1, the second parameter index 2, and so on.
This is important when you go to set the values using the various set
methods in the PreparedStatement interface.
Step 2: Setting the Parameters
Before a prepared statement can be executed, each of its parameters must be
assigned a value. The PreparedStatement interface contains a set method for
each of the possible data types of a parameter. Each set method takes in an
index to denote which parameter to set. For example, if the data type of the
parameter is a double, then you use the method:
public void setDouble(int index, double value).
Sets the specified index
to the double value argument.
The following statements prepare a statement and assign each of its four
parameters a value using the appropriate set method:
PreparedStatement insert = connection.prepareStatement(
“INSERT INTO Employees VALUES (?, ?, ?, ?)”);
insert.setDouble(2, 2.50);
insert.setInt(1, 103);
insert.setString(3, “George”);
insert.setString(4, “Washington”);
Notice that the order in which you set the parameters does not matter, as
long as you set a value for each parameter of the prepared statement.
Step 3: Executing a Prepared Statement
After the values of all the parameters are set, the prepared statement is exe-
cuted using one of the following methods in the PreparedStatement interface:
public ResultSet executeQuery() throws SQLException. Use this method
if the SQL statement returns a result set, like a SELECT statement.
public int executeUpdate() throws SQLException. Use this method for
statements like INSERT, UPDATE, or DELETE. The return value is the
number of rows affected.
public boolean execute() throws SQLException. This method executes
any type of SQL statement. Use the getResultSet() method to obtain the
result set if one is created.
To demonstrate prepared statements, I added a changeCategory() method to
the MovieDatabase class that changes the category of a movie in the database.
Search WWH ::




Custom Search