Java Reference
In-Depth Information
authorBooks.setString(
1
,
"Deitel"
);
authorBooks.setString(
2
,
"Paul"
);
Method
setString
's first argument represents the parameter number being set, and the
second argument is that parameter's value. Parameter numbers are
counted from 1
, starting
with the first question mark (
?
). When the program executes the preceding
Prepared-
Statement
with the parameter values set above, the SQL passed to the database is
SELECT
LastName, FirstName, Title
FROM
Authors
INNER JOIN
AuthorISBN
ON
Authors.AuthorID=AuthorISBN.AuthorID
INNER JOIN
Titles
ON
AuthorISBN.ISBN=Titles.ISBN
WHERE
LastName =
'Deitel'
AND
FirstName =
'Paul'
Method
setString
automatically escapes
String
parameter values as necessary. For exam-
ple, if the last name is O'Brien, the statement
authorBooks.setString(
1
,
"O'Brien"
);
escapes the
'
character in O'Brien by replacing it with two single-quote characters, so that
the
'
appears correctly in the database.
Performance Tip 24.2
PreparedStatement
s are more efficient than
Statement
s when executing SQL statements
multiple times and with different parameter values.
Error-Prevention Tip 24.2
Use
PreparedStatement
s with parameters for queries that receive
String
values as ar-
guments to ensure that the
String
s are quoted properly in the SQL statement.
Error-Prevention Tip 24.3
PreparedStatement
s help prevent SQL injection attacks, which typically occur in SQL
statements that include user input improperly. To avoid this security issue, use
Prepared-
Statement
s in which user input can be supplied only via parameters—indicated with ?
when creating a
PreparedStatement
. Once you've created such a
PreparedStatement
,
you can use its
set
methods to specify the user input as arguments for those parameters.
Interface
PreparedStatement
provides
set
methods for each supported SQL type. It's
important to use the
set
method that is appropriate for the parameter's SQL type in the
database—
SQLException
s occur when a program attempts to convert a parameter value
to an incorrect type.
Address Book Application that Uses
PreparedStatement
s
We now present an address book app that enables you to browse existing entries, add new
entries and search for entries with a specific last name. Our
AddressBook
Java DB database
contains an
Addresses
table with the columns
addressID
,
FirstName
,
LastName
,
Email
and
PhoneNumber
. The column
addressID
is an identity column in the
Addresses
table.
Class
Person
Our address book application consists of three classes—
Person
(Fig. 24.30),
PersonQue-
ries
(Fig. 24.31) and
AddressBookDisplay
(Fig. 24.32). Class
Person
is a simple class