Java Reference
In-Depth Information
163
// close the database connection
164
public void
close()
165
{
166
try
167
{
168
connection.close();
169
}
170
catch
(SQLException sqlException)
171
{
172
sqlException.printStackTrace();
173
}
174
}
175
}
// end class PersonQueries
Fig. 24.31
|
PreparedStatements
used by the Address Book application. (Part 5 of 5.)
Creating
PreparedStatement
s
Lines 31-32 invoke
Connection
method
prepareStatement
to create the
Prepared-
Statement
named
selectAllPeople
that selects all the rows in the
Addresses
table. Lines
35-36 create the
PreparedStatement
named
selectPeopleByLastName
with a parameter.
This statement selects all the rows in the
Addresses
table that match a particular last
name. Notice the
?
character that's used to specify the last-name parameter. Lines 39-42
create the
PreparedStatement
named
insertNewPerson
with four parameters that repre-
sent the first name, last name, email address and phone number for a new entry. Again,
notice the
?
characters used to represent these parameters.
PersonQueries
Method
getAllPeople
Method
getAllPeople
(lines 52-91) executes
PreparedStatement
selectAllPeople
(line 60) by calling method
executeQuery
, which returns a
ResultSet
containing the
rows that match the query (in this case, all the rows in the
Addresses
table). Lines 61-71
place the query results in an
ArrayList
of
Person
objects, which is returned to the caller
at line 90. Method
getPeopleByLastName
(lines 94-135) uses
PreparedStatement
meth-
od
setString
to set the parameter to
selectPeopleByLastName
(line 101). Then, line 104
executes the query and lines 106-115 place the query results in an
ArrayList
of
Person
objects. Line 134 returns the
ArrayList
to the caller.
PersonQueries
Methods
addPerson
and
Close
Method
addPerson
(lines 138-161) uses
PreparedStatement
method
setString
(lines
146-149) to set the parameters for the
insertNewPerson
PreparedStatement
. Line 152
uses
PreparedStatement
method
executeUpdate
to insert the new record. This method
returns an integer indicating the number of rows that were updated (or inserted) in the
database. Method
close
(lines 164-174) simply closes the database connection.
Class
AddressBookDisplay
The
AddressBookDisplay
(Fig. 24.32) application uses a
PersonQueries
object to inter-
act with the database. Line 59 creates the
PersonQueries
object. When the user presses
the
Browse All Entries
JButton
, the
browseButtonActionPerformed
handler (lines 309-
335) is called. Line 313 calls the method
getAllPeople
on the
PersonQueries
object to
obtain all the entries in the database. The user can then scroll through the entries using the