Java Reference
In-Depth Information
4
import java.sql.DriverManager;
5
6
import java.sql.PreparedStatement;
import java.sql.ResultSet;
7
import java.sql.SQLException;
8
import java.util.List;
9
import java.util.ArrayList;
10
11
public class PersonQueries
12
{
13
private static final String URL = "jdbc:derby:AddressBook" ;
14
private static final String USERNAME = "deitel" ;
15
private static final String PASSWORD = "deitel" ;
16
17
private Connection connection; // manages connection
18
private PreparedStatement selectAllPeople;
private PreparedStatement selectPeopleByLastName;
private PreparedStatement insertNewPerson;
19
20
21
22
// constructor
23
public PersonQueries()
24
{
25
try
26
{
27
connection =
28
DriverManager.getConnection( URL , USERNAME , PASSWORD );
29
30
// create query that selects all entries in the AddressBook
selectAllPeople =
connection.prepareStatement( "SELECT * FROM Addresses" );
31
32
33
34
// create query that selects entries with a specific last name
selectPeopleByLastName = connection.prepareStatement(
"SELECT * FROM Addresses WHERE LastName = ?" );
35
36
37
38
// create insert that adds a new entry into the database
insertNewPerson = connection.prepareStatement(
"INSERT INTO Addresses " +
"(FirstName, LastName, Email, PhoneNumber) " +
"VALUES (?, ?, ?, ?)" );
39
40
41
42
43
}
44
catch (SQLException sqlException)
45
{
46
sqlException.printStackTrace();
47
System.exit( 1 );
48
}
49
}
50
51
// select all of the addresses in the database
52
public List< Person > getAllPeople()
53
{
54
List< Person > results = null ;
55
ResultSet resultSet = null ;
56
Fig. 24.31 | PreparedStatements used by the Address Book application. (Part 2 of 5.)
Search WWH ::




Custom Search