Accessing Databases with...
Transcript of Accessing Databases with...
1
© 1992-2007 Pearson Education, Inc. All rights reserved.
25Accessing
Databases withJDBC
2
© 1992-2007 Pearson Education, Inc. All rights reserved.
OBJECTIVESIn this chapter you will learn: Relational database concepts. To use Structured Query Language (SQL) to retrieve
data from and manipulate data in a database. To use the JDBC™ API of package java.sql to access
databases. To use the RowSet interface from package javax.sql to
manipulate databases. To use JDBC 4.0’s automatic JDBC driver discovery. To use PreparedStatements to create precompiled SQL
statements with parameters. How transaction processing makes database
applications more robust.
3
© 1992-2007 Pearson Education, Inc. All rights reserved.
25.1 Introduction25.2 Relational Databases25.3 Relational Database Overview: The books Database25.4 SQL
25.4.1 Basic SELECT Query25.4.2 WHERE Claus25.4.3 ORDER BY Claus25.4.4 Merging Data from Multiple Tables: INNER JOIN
25.4.5 INSERT Statement25.4.6 UPDATE Statement25.4.7 DELETE Statement
25.5 Instructions for installing MySQL and MySQLConnector/J
4
© 1992-2007 Pearson Education, Inc. All rights reserved.
25.6 Instructions for Setting Up a MySQL User Account25.7 Creating Database book in MySQL25.8 Manipulating Databases with JDBC
25.8.1 Connecting to and Querying a Database25.8.2 Querying the books Database
25.9 RowSet Interface25.10 Java DB/Apache Derby25.11 PreparedStatements
25.12 Stored Procedures25.13 Transaction Processing25.14 Wrap-Up25.15 Web Resources and Recommended Readings
5
© 1992-2007 Pearson Education, Inc. All rights reserved.
25.1 Introduction
Database– Collection of data
DBMS– Database management system– Storing and organizing data
SQL– Relational database– Structured Query Language
6
© 1992-2007 Pearson Education, Inc. All rights reserved.
25.1 Introduction (Cont.)
RDBMS– Relational database management system– MySQL
- Open source- Available for both Windows and Linux- dev.mysql.com/downloads/mysql/4.0.hml
JDBC– Java Database Connectivity– JDBC driver
- Enable Java applications to connect to database- Enable programmers to manipulate databases using JDBC
7
© 1992-2007 Pearson Education, Inc. All rights reserved.
Software Engineering Observation 25.1
Using the JDBC API enables developers tochange the underlying DBMS withoutmodifying the Java code that accesses thedatabase.
8
© 2005 Pearson Education, Inc. All rights reserved.
25.2 Relational Databases
• Relational database– Table
• Rows, columns– Primary key
• Unique data
• SQL queries– Specify which data to select from a table
9
© 1992-2007 Pearson Education, Inc. All rights reserved.
Fig. 25.1 | Employee table sample data.
10
© 1992-2007 Pearson Education, Inc. All rights reserved.
Fig. 25.2 | Result of selecting distinct Department and Locationdata from table Employee.
11
© 2005 Pearson Education, Inc. All rights reserved.
25.3 Relational Database Overview: Thebooks Database
• Sample books database– Four tables
• authors– authorID, firstName, lastName
• titles– isbn, title, editionNumber, copyright, publisherID,
imageFile, price• authorISBN
– authorID, isbn
12
© 1992-2007 Pearson Education, Inc. All rights reserved.
Column Description
authorID Author’s ID number in the database. In the books database, this integer
column is defined as autoincremented —for each row inserted in this table, the authorID value is increased by 1 automatically to ensure
that each row has a unique authorID . This column represents the
table’s primary key.
firstName Author’s first name (a string).
lastName Author’s last name (a string).
Fig. 25.3 | authors table from the books database.
13
© 1992-2007 Pearson Education, Inc. All rights reserved.
authorID firstName lastName
1 Harvey Deitel
2 Paul Deitel
3 Andrew Goldberg
4 David Choffnes
Fig. 25.4 | Sample data from the authors table.
14
© 2005 Pearson Education, Inc. All rights reserved.
25.3 Relational Database Overview: Thebooks Database (Cont.)
• Foreign key– A column
• matches the primary key column in another table– Helps maintain the Rule of Referential Integrity
• Every foreign key value must appear as another table’sprimary key value
15
© 1992-2007 Pearson Education, Inc. All rights reserved.
Column Description
authorID The author’s ID number, a foreign key to the authors table.
isbn The ISBN for a book, a foreign key to the titles table.
Fig. 25.5 | authorISBN table from the books database.
16
© 1992-2007 Pearson Education, Inc. All rights reserved.
authorID isbn authorID isbn
1 0131869000 2 0131450913
2 0131869000 1 0131828274
1 0131483986 2 0131828274
2 0131483986 3 0131450913
1 0131450913 4 0131828274
Fig. 25.6 | Sample data from the authorISBN table of books.
17
© 1992-2007 Pearson Education, Inc. All rights reserved.
Column Description
isbn
ISBN of the book (a string). The table’s primary key. ISBN is an abbreviation for “International Standard Book Number” —a numbering scheme that publishers use to give every book a unique identification number.
title Title of the book (a string).
editionNumber Edition number of the book (an integer).
copyright Copyright year of the book (a string).
Fig. 25.7 | titles table from the books database.
18
© 1992-2007 Pearson Education, Inc. All rights reserved.
isbn title editionNumber copyright
0131869000 Visual Basic How to Program 3 2006
0131525239 Visual C# How to Program 2 2006
0132222205 Java How to Program 7 2007
0131857576 C++ How to Program 5 2005
0132404168 C How to Program 5 2007
0131450913 Internet & World Wide Web
How to Program
3 2004
Fig. 25.8 | Sample data from the titles table of the books database.
19
© 2005 Pearson Education, Inc. All rights reserved.
25.3 Relational Database Overview: Thebooks Database (Cont.)
• Entity-relationship (ER) diagram– Tables in the database– Relationships among tables
• Rule of Entity Integrity– Primary key uniquely identifies each row– Every row must have a value for every column of the
primary key– Value of the primary key must be unique in the table
20
© 1992-2007 Pearson Education, Inc. All rights reserved.
Fig. 25.9 | Table relationships in the books database.
21
© 1992-2007 Pearson Education, Inc. All rights reserved.
Common Programming Error 25.1
Not providing a value for every columnin a primary key breaks the Rule ofEntity Integrity and causes the DBMS toreport an error.
22
© 1992-2007 Pearson Education, Inc. All rights reserved.
Common Programming Error 25.2
Providing the same value for the primarykey in multiple rows causes the DBMS toreport an error.
23
© 1992-2007 Pearson Education, Inc. All rights reserved.
Common Programming Error 25.3
Providing a foreign-key value that does notappear as a primary-key value in anothertable breaks the Rule of ReferentialIntegrity and causes the DBMS to reportan error.
24
© 2005 Pearson Education, Inc. All rights reserved.
25.4 SQL
• SQL keywords– SQL queries and statements
25
© 1992-2007 Pearson Education, Inc. All rights reserved.
SQL keyword Description
SELECT Retrieves data from one or more tables.
FROM Tables involved in the query. Required in every SELECT.
WHERE Criteria for selection that determine the rows to be retrieved, deleted or updated. Optional in a SQL query or a SQL statement.
GROUP BY Criteria for grouping rows. Optional in a SELECT query.
ORDER BY Criteria for ordering rows. Optional in a SELECT query.
INNER JOIN Merge rows from multiple tables.
INSERT Insert rows into a specified table.
UPDATE Update rows in a specified table.
DELETE Delete rows from a specified table.
Fig. 25.10 | SQL query keywords.
26
© 2005 Pearson Education, Inc. All rights reserved.
25.4.1 Basic SELECT Query
• Simplest format of a SELECT query– SELECT * FROM tableName
• SELECT * FROM authors
• Select specific fields from a table– SELECT authorID, lastName FROM authors
27
© 1992-2007 Pearson Education, Inc. All rights reserved.
authorID lastName
1 Deitel
2 Deitel
3 Goldberg
4 Choffnes
Fig. 25.11 | Sample authorID and lastName data from the authors table.
28
© 1992-2007 Pearson Education, Inc. All rights reserved.
Software Engineering Observation 25.2
For most queries, the asterisk (*) should not be used to specifycolumn names. In general, you process results by knowing inadvance the order of the columns in the result—for example,selecting authorID and lastName from table authors ensuresthat the columns will appear in the result with authorID as thefirst column and lastName as the second column. Programstypically process result columns by specifying the column numberin the result (starting from number 1 for the first column).Selecting columns by name also avoids returning unneededcolumns and protects against changes in the actual order of thecolumns in the table(s).
29
© 1992-2007 Pearson Education, Inc. All rights reserved.
Common Programming Error 25.4
If you assume that the columns are alwaysreturned in the same order from a query thatuses the asterisk (*), the program mayprocess the results incorrectly. If the columnorder in the table(s) changes or if additionalcolumns are added at a later time, the orderof the columns in the result would changeaccordingly.
30
© 2005 Pearson Education, Inc. All rights reserved.
25.4.2 WHERE Clause
• specify the selection criteria– SELECT columnName1, columnName2, … FROM
tableName WHERE criteria• SELECT title, editionNumber, copyright
FROM titlesWHERE copyright > 2002
31
© 1992-2007 Pearson Education, Inc. All rights reserved.
Portability Tip 25.1
See the documentation for your databasesystem to determine whether SQL is casesensitive on your system and to determinethe syntax for SQL keywords (i.e., shouldthey be all uppercase letters, all lowercaseletters or some combination of the two?).
32
© 1992-2007 Pearson Education, Inc. All rights reserved.
title editionNumber copyright
Visual C# How to Program 2 2006
Visual Basic 2005 How to Program 3 2006
Java How to Program 7 2007
C How to Program 5 2007
Fig. 25.12 | Sampling of titles with copyrights after 2005 from table titles.
33
© 2005 Pearson Education, Inc. All rights reserved.
25.4.2 WHERE Clause (Cont.)
• WHERE clause condition operators– <, >, <=, >=, =, <>– LIKE
• wildcard characters % and _• SELECT authorID, firstName, lastName
FROM authorsWHERE lastName LIKE ‘D%’
34
© 1992-2007 Pearson Education, Inc. All rights reserved.
authorID firstName lastName
1 Harvey Deitel
2 Paul Deitel
Fig. 25.13 | Authors whose last name starts with D from the authors table.
35
© 1992-2007 Pearson Education, Inc. All rights reserved.
Portability Tip 25.2
Read your database system’s documentationcarefully to determine whether your systemsupports the LIKE operator. The SQL wediscuss is supported by most RDBMSs, but itis always a good idea to check the features ofSQL that are supported by your RDBMS.
36
© 2005 Pearson Education, Inc. All rights reserved.
25.4.2 WHERE Clause (Cont.)
• SELECT authorID, firstName, lastNameFROM authorsWHERE lastName LIKE ‘_i%’
37
© 1992-2007 Pearson Education, Inc. All rights reserved.
authorID firstName lastName
3 Andrew Goldberg
Fig. 25.14 | The only author from the authors table whose last namecontains o as the second letter.
38
© 2005 Pearson Education, Inc. All rights reserved.
25.4.3 ORDER BY Clause
• Optional ORDER BY clause– SELECT columnName1, columnName2, … FROM
tableName ORDER BY column ASC• SELECT authorID, firstName, lastName
FROM authorsORDER BY lastName ASC
– SELECT columnName1, columnName2, … FROMtableName ORDER BY column DESC
• SELECT authorID, firstName, lastNameFROM authorsORDER BY lastName DESC
39
© 1992-2007 Pearson Education, Inc. All rights reserved.
authorID firstName lastName
4 David Choffnes
1 Harvey Deitel
2 Paul Deitel
3 Andrew Goldberg
Fig. 25.15 | Sample data from table authors in ascending order by lastName.
40
© 1992-2007 Pearson Education, Inc. All rights reserved.
authorID firstName lastName
3 Andrew Goldberg
1 Harvey Deitel
2 Paul Deitel
4 David Choffnes
Fig. 25.16 | Sample data from table authors in descending order by lastName.
41
© 2005 Pearson Education, Inc. All rights reserved.
25.4.3 ORDER BY Clause (Cont.)
• ORDER BY multiple fields– ORDER BY column1 sortingOrder, column2 sortingOrder, …
• SELECT authorID, firstName, lastNameFROM authorsORDER BY lastName, firstName
42
© 1992-2007 Pearson Education, Inc. All rights reserved.
authorID firstName lastName
4 David Choffnes
1 Harvey Deitel
2 Paul Deitel
4 Andrew Goldberg
Fig. 25.17 | Sample data from authors in ascending orderby lastName and firstName.
43
© 2005 Pearson Education, Inc. All rights reserved.
25.4.3 ORDER BY Clause (Cont.)
• Combine the WHERE and ORDER BY clauses• SELECT isbn, title, editionNumber, copyright, price
FROM titles WHERE title LIKE ‘%How to Program’ORDER BY title ASC
44
© 1992-2007 Pearson Education, Inc. All rights reserved.
isbn title edition - Number copy- right
0132404168 C How to Program 5 2007
0131857576 C++ How to Program 5 2005
0131450913 Internet and World Wide Web How to Program 3 2004
0132222205 Java How to Program 7 2007
0131869000 Visual Basic 2005 How to Program 3 2006
013152539 Visual C# How to Program 2 2006
Fig. 25.18 | Sampling of books from table titles whose titles end withHow to Program in ascending order by title.
45
© 2005 Pearson Education, Inc. All rights reserved.
25.4.4 Merging Data from Multiple Tables:INNER JOIN
• Split related data into separate tables• Join the tables
– Merge data from multiple tables into a single view– INNER JOIN
• SELECT columnName1, columnName2, … FROM table1
INNER JOIN table2 ON table1.columnName = table2.column2Name• SELECT firstName, lastName, isbn
FROM authors, authorISBN INNER JOIN authorISBN
ON authors.authorID = authorISBN.authorID ORDER BY lastName, firstName
46
© 1992-2007 Pearson Education, Inc. All rights reserved.
firstName lastName isbn firstName lastName isbn
David Choffnes 0131828274 Paul Deitel 0131525239
Harvey Deitel 0131525239 Paul Deitel 0132404168
Harvey Deitel 0132404168 Paul Deitel 0131869000
Harvey Deitel 0131869000 Paul Deitel 0132222205
Harvey Deitel 0132222205 Paul Deitel 0131450913
Harvey Deitel 0131450913 Paul Deitel 0131525239
Harvey Deitel 0131525239 Paul Deitel 0131857576
Harvey Deitel 0131857576 Paul Deitel 0131828274
Harvey Deitel 0131828274 Andrew Goldberg 0131450 913
Fig. 25.19 | Sampling of authors and ISBNs for the books they have written inascending order by lastName and firstName.
47
© 1992-2007 Pearson Education, Inc. All rights reserved.
Software Engineering Observation 25.3
If a SQL statement includes columns with thesame name from multiple tables, the statementmust precede those column names with their tablenames and a dot (e.g., authors.authorID).
48
© 1992-2007 Pearson Education, Inc. All rights reserved.
Common Programming Error 25.5
Failure to qualify names for columnsthat have the same name in two or moretables is an error.
49
© 2005 Pearson Education, Inc. All rights reserved.
25.4.5 INSERT Statement
• Insert a row into a table– INSERT INTO tableName ( columnName1, … , columnNameN ) VALUES ( value1, … , valueN )
• INSERT INTO authors ( firstName, lastName ) VALUES ( ‘Sue’, ‘Smith’ )
50
© 1992-2007 Pearson Education, Inc. All rights reserved.
authorID firstName lastName
1 Harvey Deitel
2 Paul Deitel
3 Andrew Goldberg
4 David Choffnes
5 Sue Smith
Fig. 25.20 | Sample data from table Authors after an INSERT operation.
51
© 1992-2007 Pearson Education, Inc. All rights reserved.
Common Programming Error 25.6
It is normally an error to specify avalue for an autoincrement column.
52
© 1992-2007 Pearson Education, Inc. All rights reserved.
Common Programming Error 25.7
SQL uses the single-quote (') character as a delimiterfor strings. To specify a string containing a singlequote (e.g., O’Malley) in a SQL statement, the stringmust have two single quotes in the position where thesingle-quote character appears in the string (e.g.,'O''Malley'). The first of the two single-quotecharacters acts as an escape character for the second.Not escaping single-quote characters in a string that ispart of a SQL statement is a SQL syntax error.
53
© 2005 Pearson Education, Inc. All rights reserved.
25.4.6 UPDATE Statement
• Modify data in a table– UPDATE tableName SET columnName1 = value1, … , columnNameN = valueN
WHERE criteria• UPDATE authors SET lastName = ‘Jones’ WHERE lastName = ‘Smith’ AND firstName = ‘Sue’
54
© 1992-2007 Pearson Education, Inc. All rights reserved.
authorID firstName lastName
1 Harvey Deitel
2 Paul Deitel
3 Andrew Goldberg
4 David Choffnes
5 Sue Jones
Fig. 25.21 | Sample data from table authors after an UPDATE operation.
55
© 2005 Pearson Education, Inc. All rights reserved.
25.4.7 DELETE Statement
• Remove data from a table– DELETE FROM tableName WHERE criteria
• DELETE FROM authors WHERE lastName = ‘Jones’ AND firstName = ‘Sue’
56
© 1992-2007 Pearson Education, Inc. All rights reserved.
authorID firstName lastName
1 Harvey Deitel
2 Paul Deitel
3 Andrew Goldberg
4 David Choffnes
Fig. 25.22 | Sample data from table authors after a DELETE operation.
57
© 2005 Pearson Education, Inc. All rights reserved.
25.5 Instructions to Install MySQL andMySQL Connector/J
• Install MySQL– Platform-specific installation requirements:
• dev.mysql.com/doc/refman/5.0/en/general-installation-issues.html
– Download your platform’s installer from:• dev.mysql.com/downloads/mysql/5.0.html• Need only the Windows Essentials package on Microsoft
Windows– Follow installation instructions for your platform:
• dev.mysql.com/doc/refman/5.0/en/installing.html
58
© 2005 Pearson Education, Inc. All rights reserved.
25.5 Instructions to Install MySQL andMySQL Connector/J
• MySQL Server Instance Configuration Wizard– Click Next > then select Standard Configuration and
clickNext > again.
– Not necessary to install MySQL as a Windows service forour examples
• Uncheck Install as a Windows Service• Check Include Bin Directory in Windows PATH
– Click Next > then click Execute to perform the serverconfiguration.
– Click Finish to close the wizard.
59
© 2005 Pearson Education, Inc. All rights reserved.
25.5 Instructions to Install MySQL andMySQL Connector/J
• Install MySQL Connector/J– Must install Connector/J JDBC driver from:
• dev.mysql.com/downloads/connector/j/5.0.html
– Download mysql-connector-java-5.0.4.zip– Extract mysql-connector-java-5.0.4.zip to your hard disk into
the folder mysql-connector-java-5.0.4– Documentation for MySQL Connector/J is in
connector-j.pdf in the docs subdirectory ofmysql-connector-java-5.0.4
– Docs also online at dev.mysql.com/doc/connector/j/en/connector-j.html
60
© 2005 Pearson Education, Inc. All rights reserved.
25.6 Instructions on Setting MySQL UserAccount
• Set up a user account– Start database server
• mysqld-nt.exe on Windows– Start the MySQL monitor
• mysql –h localhost –u root– Select the built-in database mysql
• USE mysql;
– Add the user account jhtp7 and specify privileges• create user 'jhtp7'@'localhost' identified by 'jhtp7';• grant select, insert, update, delete, create, drop, references, execute
on *.* to 'jhtp7'@'localhost';– Exit the MySQL Monitor
• exit;
61
© 2005 Pearson Education, Inc. All rights reserved.
25.7 Creating Database books in MySQL
• Create books database– Open Command Prompt and change to the directory
containing the SQL script books.sql– Start the MySQL monitor
• mysql –h localhost –u jhtp7 –p– Execute the script
• source books.sql;
– Exit the MySQL Monitor• exit;
62
© 2005 Pearson Education, Inc. All rights reserved.
25.8 Manipulating Databases with JDBC
• Connect to a database• Query the database• Display the results of the query in JTable
63
© 2005 Pearson Education, Inc. All rights reserved.
25.8.1 Connecting to and Querying aDatabase
• DisplayAuthors– Retrieves the entire authors table– Displays the data in the standard output stream– Example illustrates
• Connect to the database• Query the database• Process the result
64
© 1992-2007 Pearson Education, Inc. All rights reserved.
1 // Fig. 25.23: DisplayAuthors.java
2 // Displaying the contents of the authors table.
3 import java.sql.Connection;
4 import java.sql.Statement;
5 import java.sql.DriverManager;
6 import java.sql.ResultSet;
7 import java.sql.ResultSetMetaDat a ;
8 import java.sql.SQLException;
9
10 public c l ass DisplayAuthors
11 {
12 // JDBC driver name and database URL
13 static final String DR IVER = "com.mysql. jdbc.Driver" ;
14 stat ic final St ring DATABASE_URL = "jdbc:mysql://localhost/books" ;
15
16 // launch the application
17 public stat ic vo id main( String args[] )
18 {
19 Connection connection = null ; // manages connection
20 Statement statement = null ; // query statement
21 ResultSet resultSet = null ; // manages results
22
23 // connect to database books and query database
24 t r y
25 {
26 // load the driver class
27 Class.forName( DR IVER );
28
Outline
DisplayAuthors .java
(1 of 3 )
Imports for the JDBC classes andinterfaces from package java.sql
Declare a String constantthat specifies the JDBCdriver’s class name
Loads the class definitionfor the database driver.
Declare a Stringconstant that specifiesthe database URL
65
© 1992-2007 Pearson Education, Inc. All rights reserved.
29 // establish connection to database
30 connection =
31 DriverManager.getConnection( DATABASE_URL, "jhtp7" , "jhtp7" );
32
33 // create Statement for querying database
34 statement = connection.createStatement();
35
36 // query database
37 resultSet = statement.executeQuery(
38 "SELECT authorID, firstName, lastName FROM authors" );
39
40 // process query results
41 ResultSetMetaData metaData = resultSet.getMetaData();
42 int numberOfColumns = metaData.getColumnCount();
43 System.out.println( "Authors Table of Books Database:\n" );
44
45 f o r ( int i = 1; i <= numberOfColumns; i++ )
46 System.out.printf( "%- 8 s\t" , metaData.getColumnName( i ) );
47 System. out.println();
48
49 while ( resultSet.next() )
50 {
51 f o r ( int i = 1; i <= numberOfColumns; i++ )
52 System.out.printf( "%- 8 s\t" , resultSet.getObject( i ) ) ;
53 System.out.p rintln();
54 } // end while
55 } // end try
Outline
DisplayAuthors .java
(2 of 3 )
Invokes Connection methodcreateStatement to obtain an objectthat implements interface Statement.Use the Statement object’s
executeQuery method toexecute a query that selectsall the author informationfrom table authors.
Obtains the metadatafor the ResultSet.Uses ResultSetMetaData
method getColumnCountto retrieve the number ofcolumns in the ResultSet.Obtain column
name using methodgetColumnNamePosition the ResultSet cursor to the first
row in the ResultSet with method next
Extract the contentsof one column in thecurrent row
Initialize aConnection referencecalled connection.
66
© 1992-2007 Pearson Education, Inc. All rights reserved.
56 catch ( SQLException sqlException ) 57 { 58 sqlException.printStackTrace(); 59 } // end catch 60 catch ( ClassNotFoundException classNotFound ) 61 { 62 classNotFound.printStackTrace(); 63 } // end catch 64 finally // ensure resultSet, statement and connection are closed 65 { 66 t r y 67 { 68 resultSet.close(); 69 statement.close(); 70 connection.close(); 71 } // end try 72 catch ( Exception exception ) 73 { 74 exception.printStackTrace(); 75 } // end catch 76 } // end finally 77 } // end main 78 } // end class DisplayAuthors Authors Table of Books Database: authorID firstName lastName 1 Harvey Deitel 2 Paul Deitel 3 Andrew Goldberg 4 David Choffnes
Outline
DisplayAuthors .java
(3 of 3 )
Catch SQLException, which isthrown if the query execution orResultSet process fails
ClassNotFoundException isthrown if the class loadercannot locate the driver class
Close the Statement andthe database Connection.
67
© 1992-2007 Pearson Education, Inc. All rights reserved.
Software Engineering Observation 25.4
Most major database vendors provide theirown JDBC database drivers, and manythird-party vendors provide JDBC drivers aswell. For more information on JDBC drivers,visit the Sun Microsystems JDBC Web site,servlet.java.sun.com/products/jdbc/drivers.
68
© 1992-2007 Pearson Education, Inc. All rights reserved.
Software Engineering Observation 25.5
Most database management systems requirethe user to log in before accessing thedatabase contents. DriverManager methodgetConnection is overloaded with versionsthat enable the program to supply the username and password to gain access.
69
© 1992-2007 Pearson Education, Inc. All rights reserved.
RDBMS Database URL format
MySQL jdbc:mysql:// hostname : portNumber /databaseName
ORACLE jdbc:oracle:thin:@ hostname : portNumber : databaseName
DB2 jdbc:db2: hostname : portNumber /databaseName
Java DB/Apache Derby jdbc:derby: dataBaseName (embedded) !
jdbc:derb y:// hostname : portNumber /databaseName (network) !
Microsoft SQL Server jdbc:sqlserver:// hostname : portNumber ; databaseName=dataBaseName
Sybase jdbc:sybase:Tds: hostname : portNumber /databaseName
Fig. 25.24 | Popular JDBC database URL formats.
70
© 1992-2007 Pearson Education, Inc. All rights reserved.
Software Engineering Observation 25.6
Metadata enables programs to processResultSet contents dynamically whendetailed information about theResultSet is not known in advance.
71
© 1992-2007 Pearson Education, Inc. All rights reserved.
Common Programming Error 25.8
Initially, a ResultSet cursor is positionedbefore the first row. Attempting to access aResultSet’s contents before positioning theResultSet cursor to the first row withmethod next causes a SQLException.
72
© 1992-2007 Pearson Education, Inc. All rights reserved.
Performance Tip 25.1
If a query specifies the exact columns to selectfrom the database, the ResultSet contains thecolumns in the specified order. In this case, usingthe column number to obtain the column’s valueis more efficient than using the column name.The column number provides direct access to thespecified column. Using the column namerequires a search of the column names to locatethe appropriate column.
73
© 1992-2007 Pearson Education, Inc. All rights reserved.
Common Programming Error 25.9
Specifying column number 0 whenobtaining values from a ResultSetcauses a SQLException.
74
© 1992-2007 Pearson Education, Inc. All rights reserved.
Common Programming Error 25.10
Attempting to manipulate a ResultSet afterclosing the Statement that created theResultSet causes a SQLException. Theprogram discards the ResultSet when thecorresponding Statement is closed.
75
© 1992-2007 Pearson Education, Inc. All rights reserved.
Software Engineering Observation 25.7
Each Statement object can open only oneResultSet object at a time. When aStatement returns a new ResultSet, theStatement closes the prior ResultSet. Touse multiple ResultSets in parallel,separate Statement objects must return theResultSets.
76
© 2005 Pearson Education, Inc. All rights reserved.
25.8.2 Querying the books Database
• Allow the user to enter any query into theprogram
• Display the results of a query in a JTable
77
© 1992-2007 Pearson Education, Inc. All rights reserved.
1 // Fig. 25.25: ResultSetTableModel.java
2 // A TableModel that supplies ResultSet data to a JTable.
3 import java.sql.Connection;
4 import java.sql.Statement;
5 import java.sql.DriverManager;
6 import java.sql.ResultSet;
7 import java.sql.Re sultSetMetaData;
8 import java.sql.SQLException;
9 import javax.swing.table.AbstractTableModel;
10
11 // ResultSet rows and columns are counted from 1 and JTable
12 // rows and columns are counted from 0. When processing
13 // ResultSet rows or columns for use in a JTable, it is
14 // necessary to add 1 to the row or column number to manipulate
15 // the appropriate ResultSet column (i.e., JTable column 0 is
16 // ResultSet column 1 and JTable row 0 is ResultSet row 1).
17 public c l a s s ResultSetTableModel extends AbstractTableModel
18 {
19 pr ivate Connection connection;
20 pr ivate Statement statement;
21 pr ivate ResultSet resultSet;
22 pr ivate ResultSetMetaData metaData;
23 pr ivate int numberOfRows;
24
25 // keep track of database connection status
26 pr ivate boolean connectedToDatabase = fa lse ;
27
Outline
ResultSetTableModel.java
(1 of 7 )
Class ResultSetTableModel extendsclass AbstractTableModel, whichimplements interface TableModel.
Instance variable keeps trackof database connection status
78
© 1992-2007 Pearson Education, Inc. All rights reserved.
28 // constructor initializes resultSet and obtains its meta data object;
29 // determines number of rows
30 public ResultSetTableModel( String driver, String url, String username,
31 String password, String query )
32 th rows SQLException, ClassNotFoundException
33 {
34 Class.forName( driver );
35 // connect to database
36 connection = DriverManager.getConnection( url, username, password );
37
38 // create Statement to query database
39 statement = connection.createStatement(
40 ResultSet.TYPE_SCROLL_INSENSITIVE,
41 ResultSet.CONCUR_READ_ONLY );
42
43 // update database connection status
44 connectedToDatabase = t rue;
45
46 // set query and execute it
47 setQuery( query );
48 } // end constructor ResultSetTableModel
49
Outline
ResultSetTableModel.java
(2 of 7 )
Establishes a connectionto the database.
Invokes Connectionmethod createStatement tocreate a Statement object.
Constructor accepts five Stringarguments—the driver classname, the database URL, theusername, the password and thedefault query to perform
Indicate that connect todatabase is successful
Invokes ResultSetTableModelmethod setQuery to performthe default query.
79
© 1992-2007 Pearson Education, Inc. All rights reserved.
50 // get class that represents column type
51 public Class getColumnClass( int column ) th rows IllegalStateException
52 {
53 // ensure database connection is available
54 i f ( !connectedToDatabase )
55 th row new IllegalStateException( "Not Connected to Database" );
56
57 // determine Java class of column
58 t r y
59 {
60 String className = metaData.getColumnClassName( column + 1 );
61
62 // return Class object that represents className
63 return Class.forName( className );
64 } // end try
65 catch ( Exception exception )
66 {
67 excepti on.pr intStackTrace();
68 } // end catch
69
70 return Object. c l ass ; // if problems occur above, assume type Object
71 } // end method getColumnClass
72
73 // get number of columns in ResultSet
74 public int getColu mnCount() th rows IllegalStateException
75 {
76 // ensure database connection is available
77 i f ( !connectedToDatabase )
78 th row new IllegalStateException( "Not Connected to Database" ) ;
79
Outline
ResultSetTableModel.java
(3 of 7 )
Override method getColumnClass to obtain aClass object that represents the superclass ofall objects in a particular column
Verify databaseconnection status
Loads the class definition for the class andreturns the corresponding Class object.
Returns thedefault type.
Obtains the fully qualified classname for the specified column.
Override method getColumnCount toobtain the number of columns in themodel’s underlying ResultSet
80
© 1992-2007 Pearson Education, Inc. All rights reserved.
80 // determine number of columns
81 t r y
82 {
83 return metaData.getColumnCount();
84 } // end try
85 catch ( SQLException sqlException )
86 {
87 sqlException.printStackTrace();
88 } // end catch
89
90 return 0; // if problems occur above, return 0 for number of columns
91 } // end method getColumnCount
92
93 // get name of a particular column in ResultSet
94 public String getColumnName( int co lumn ) th rows IllegalStateException
95 {
96 // ensure database connection is available
97 i f ( !connectedToDatabase )
98 th row new IllegalStateException( "Not Connected to Database" );
99
100 // determine col umn name
101 t r y
102 {
103 return metaData.getColumnName( column + 1 );
104 } // end try
105 catch ( SQLException sqlException )
106 {
107 sqlException.printStackTrace();
108 } // end catch
109
Outline
ResultSetTableModel.java
(4 of 7 )
Obtains the number ofcolumns in the ResultSet.
Override method getColumnNameto obtain the name of the column inthe model’s underlying ResultSet
Obtains the column namefrom the ResultSet.
81
© 1992-2007 Pearson Education, Inc. All rights reserved.
110 return "" ; // if problems, return empty string for column name
111 } // end method getColumnName
112
113 // return number of rows in ResultSet
114 public int getRowCount() th rows IllegalStateException
115 {
116 // ensure database connection is available
117 i f ( !connectedToDatabase )
118 th row new IllegalStateException( "Not Connected to Database" ) ;
119
120 return numberOfRows;
121 } // end method getRowCount
122
123 // obtain value in particular row and column
124 public Object getValueAt( int row, int column )
125 th rows IllegalStateException
126 {
127 // ensure database connection is available
128 i f ( !connectedToDatabase )
129 th row new IllegalStateException( "Not Connected to Database" );
130
131 // obtain a value at specified ResultSet row and column
132 t r y
133 {
134 resultSet.absolute( row + 1 );
135 return resu ltSet.getObject( column + 1 );
136 } // end try
Outline
ResultSetTableModel.java
(5 of 7 )Override method getColumnCount toobtain the number of rows in themodel’s underlying ResultSet
Uses ResultSet method absolute to positionthe ResultSet cursor at a specific row.
Override method getValueAt to obtain theObject in a particular row and column of themodel’s underlying ResultSet
Uses ResultSet method getObjectto obtain the Object in a specificcolumn of the current row.
82
© 1992-2007 Pearson Education, Inc. All rights reserved.
137 catch ( SQLException sqlException )
138 {
139 sqlException.printStackTrace();
140 } // end catch
141
142 return "" ; // if problems, return empty string object
143 } // end method getValueAt
144
145 // set new database query string
146 public vo id setQuery( String query )
147 th rows SQLException, IllegalStateException
148 {
149 // ensure database connection is available
150 i f ( !connectedToDatabase )
151 th row new IllegalStateException( "Not Connected to Database" );
152
153 // specify query and execute it
154 resultSet = statement.executeQuery( query );
155
156 // obtain meta data for ResultSet
157 met aData = resultSet.getMetaData();
158
159 // determine number of rows in ResultSet
160 resultSet.last(); // move to last row
161 numberOfRows = resultSet.getRow(); // get row number
162
163 // notify JTable that model has changed
164 fireTableStructureChanged();
165 } // end method setQuery
166
Outline
ResultSetTableModel.java
(6 of 7 )
Executes the query toobtain a new ResultSet.
Uses ResultSet method last toposition the ResultSet cursor atthe last row in the ResultSet.
Uses ResultSet method getRowto obtain the row number for thecurrent row in the ResultSet.
Invokes method fireTableAStructureChangedto notify any JTable using thisResultSetTableModel object as its model thatthe structure of the model has changed.
83
© 1992-2007 Pearson Education, Inc. All rights reserved.
167 // close Statement and Connection
168 public vo id disconnectFromDatabase()
169 {
170 i f ( connectedToDatabase )
171 {
172 // close Statement and Connection
173 t r y
174 {
175 resultS et.close();
176 statement.close();
177 connection.close();
178 } // end try
179 catch ( SQLException s qlException )
180 {
181 sqlException.printStackTrace();
182 } // end catch
183 finally // update database connection status
184 {
185 connectedToDatabase = fa lse ;
186 } // end finally
187 } // end if
188 } // end method disconnectFromDatabase
189 } // end class ResultSetTableModel
Outline
ResultSetTableModel.java
(7 of 7 )
Method disconnectFromDatabaseimplement an appropriate termination methodfor class ResultSetTableModel
Verify whether the connectionis already terminated
Close the Statement and Connection if aResultSetTableModel object is garbage collected.
Set connectedToDatabase to false toensure that clients do not use an instance ofResultSetTableModel after that instancehas already been terminated
84
© 1992-2007 Pearson Education, Inc. All rights reserved.
ResultSet static
type constant Description
TYPE_FORWARD_ONLY Specifies that a ResultSet ’s cursor can move only in the forward
direction (i.e., from the first row to the last row in the ResultSet ).
TYPE_SCROLL_INSENSITIVE Specifies that a ResultSet ’s cursor can scroll in either direction
and that the changes made to the ResultSet during ResultSet
processing are not reflected in the ResultSet unless the program
queries the database again.
TYPE_SCROLL_SENSITIVE Specifies that a ResultSet ’s cursor can scroll in either direction
and that the changes made to the ResultSet during ResultSet !
processing are reflected immediately in the ResultSet .!
Fig. 25.26 | ResultSet constants for specifying ResultSet type.
85
© 1992-2007 Pearson Education, Inc. All rights reserved.
Portability Tip 25.3
Some JDBC drivers do not supportscrollable ResultSets. In such cases, thedriver typically returns a ResultSet inwhich the cursor can move only forward.For more information, see your databasedriver documentation.
86
© 1992-2007 Pearson Education, Inc. All rights reserved.
Portability Tip 25.4
Some JDBC drivers do not support updatableResultSets. In such cases, the drivertypically returns a read-only ResultSet. Formore information, see your database driverdocumentation.
87
© 1992-2007 Pearson Education, Inc. All rights reserved.
Common Programming Error 25.11
Attempting to update a ResultSet when thedatabase driver does not support updatableResultSets causesSQLFeatureNotSupportedExceptions.
88
© 1992-2007 Pearson Education, Inc. All rights reserved.
Common Programming Error 25.12
Attempting to move the cursor backwardthrough a ResultSet when the databasedriver does not support backwardscrolling causes a SQLException.
89
© 1992-2007 Pearson Education, Inc. All rights reserved.
ResultSet static concurrency constant
Description
CONCUR_READ_ONLY Specifies that a ResultSet cannot be updated (i.e., changes to the ResultSet
contents cannot be reflected in the database with ResultSet ’s update methods).
CONCUR_UPDATABLE Specifies that a !ResultSet can be updated (i.e., changes to the ! ResultSet !
contents can be reflected in the database with ! ResultSet ’s update methods). !
Fig. 25.27 | ResultSet constants for specifying result properties.
90
© 1992-2007 Pearson Education, Inc. All rights reserved.
1 // Fig. 25.28: DisplayQueryResults.java
2 // Display the contents of the Authors table in the books database.
3 import java.awt.BorderLayout;
4 import java.awt.event.ActionListener;
5 import java.awt.event.ActionEvent;
6 import java.awt.event. WindowAdapter;
7 import java.awt.event.WindowEvent;
8 import java.sql.SQLException;
9 import java.util.regex.PatternSyntaxException;
10 import javax.swing.JFrame;
11 import javax.swing.JTextArea;
12 import javax.swing.JScrollPane;
13 import j avax.swing.Scrol lPaneConstants;
14 import javax.swing.JTable;
15 import javax.swing.JOptionPane;
16 import javax.swing.JButton;
17 import javax.swing.Box;
18 import javax.swing.JLabel;
19 import javax.swing.JTextField;
20 import javax.swing.R owFilter;
21 import javax.swing.table.TableRowSorter;
22 import javax.swing.table.TableModel;
23
24 public class DisplayQueryResults extends JFrame
25 {
26 // JDBC database URL, username and password
27 static final Str ing DR IVER = "com.mysql. jdbc.Driver" ;
28 static final String DATABASE_URL = "jdbc:mysql://localhost/books" ;
29 static final String USERNAME = "jhtp7" ;
30 static final String PASSWORD = "jhtp7" ;
Outline
DisplayQueryResults.java
(1 of 8 )
Declare the database driverclass name, database URL,username and password foraccessing the database
91
© 1992-2007 Pearson Education, Inc. All rights reserved.
31
32 // default query retrieves all data from authors table
33 static final String DEFAULT_QUERY = "SELECT * FROM authors";
34
35 pr ivate ResultSetTableModel tableModel;
36 pr ivate JTextArea queryArea;
37
38 // cr eate ResultSetTableModel and GUI
39 public DisplayQueryResults()
40 {
41 super( "Displaying Query Results" ) ;
42
43 // create ResultSetTableModel and display database table
44 t r y
45 {
46 // create TableModel for results of query SELECT * FROM authors
47 tableModel = new ResultSetTableModel( DR IVER, DATABASE_URL,
48 USERNAME, PASSWORD, DEFAULT_QUERY );
49
50 // set up JText Area in which user types queries
51 queryArea = new JTextArea( DEFAULT_QUERY, 3, 100 );
52 queryArea.setWrapStyleWord( t rue );
53 queryArea.setLineWrap( t rue );
54
55 JScrollPane scrollPane = new JScr ollPane( queryArea,
56 Scrol lPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
57 Scrol lPaneConstants.HORIZONTAL_SCROLLBAR_NEVER );
58
59 // set up JButton for submitting queries
60 JButton submitBut ton = new JButton( "Submit Query" ) ;
Outline
DisplayQueryResults.java
(2 of 8 )
Declare the default query
Declare tableModel to be a reference toResultSetTableModel
Create TableModelfor results of defaultquery “SELECT *FROM authors”
92
© 1992-2007 Pearson Education, Inc. All rights reserved.
61
62 // create Box to manage placement of queryArea and
63 // submitButton in GUI
64 Box boxNorth = Box.createHorizontalBox();
65 boxNorth.add( scrollPane );
66 boxNorth.add( submitButton );
67
68 // create JTable delegate for tableModel
69 JTable resultTable = new JTable( tableModel );
70
71 JLabel filterLabel = new JLabel( "Filter:" ) ;
72 f inal JTextField filterText = new JTextField( ) ;
73 JButton filterButton = new JButton( "Apply Filter" );
74 Box boxSouth = boxNorth.createHorizontalBox();
75
76 boxSouth.add( filterLabel );
77 boxSouth.add( filterText );
78 boxSouth.a dd( filterButton );
79
80 // place GUI components on content pane
81 add( boxNorth, BorderLayout.NORTH );
82 add( new JScrollPane( resultTable ), BorderLayout.CENTER );
83 add( boxSouth, BorderLayout.SOUTH );
84
85 // create event listener for submitButton
86 submitButton.addActionListener(
87
Outline
DisplayQueryResults.java
(3 of 8 )Create JTable delegatefor tableModel
93
© 1992-2007 Pearson Education, Inc. All rights reserved.
88 new ActionListener()
89 {
90 // pass query to table model
91 public void actionPerformed( ActionEvent event )
92 {
93 // perform a new query
94 t r y
95 {
96 tableModel.setQuery( queryArea.getText() );
97 } // end try
98 catch ( SQLException sqlException )
99 {
100 JOptionPane.showMessageDialog( null ,
101 sqlException.getMessage(), "Database error",
102 JOptionPane.ERROR_MESSAGE );
103
104 // try to recover from inv alid user query
105 // by executing default query
106 t r y
107 {
108 tableModel.setQuery( DEFAULT_QUERY );
109 queryArea.setText( DEFAULT_QUERY );
110 } // end try
111 catch ( SQLException sqlException2 )
112 {
113 JOptionPane.showMessageDialog( null ,
114 sqlExcep tion2.getMessage(), "Database error",
115 JOptionPane.ERROR_MESSAGE );
116
Outline
DisplayQueryResults.java
(4 of 8 )
Register an event handler for thesubmitButton that the user clicksto submit a query to the database
Invoke ResultSetTableModelmethod setQuery to executethe new query
94
© 1992-2007 Pearson Education, Inc. All rights reserved.
117 // ensure database connection is closed
118 tableModel.disconnectFromDatabase();
119
120 System.exit( 1 ); // terminate application
121 } // end inner catch
122 } // end outer catch
123 } // end actionPerformed
124 } // end ActionListener inner class
125 ); // end call to addActionListener
126
127 f inal TableRowSorter< TableModel > sorter =
128 new TableRowSorter< TableModel >( tableModel );
129 resultTable.setRowSorter( sorter );
130 setSize( 500, 250 ); // set window si z e
131 setVisible( t rue ); // display window
132
133 // create listener for filterButton
134 filterButton.addActionListener(
135 new ActionListener()
136 {
137 // pass filter text to listener
138 public void actionPerformed( ActionEvent e )
139 {
140 String text = filterText.getText();
141
142 i f ( text.length() == 0 )
143 sorter.setRowFilter( null );
144 else
145 {
146 t r y
Outline
DisplayQueryResults.java
(5 of 8 )
Ensure that the databaseconnection is closed
Set up TableRowSorter
No filter initially
95
© 1992-2007 Pearson Education, Inc. All rights reserved.
147 {
148 sorter.setRowFilter(
149 RowFilter.regexFilter( text ) );
150 } // end try
151 catch ( PatternSyntaxExceptio n pse )
152 {
153 JOptionPane.showMessageDialog( null ,
154 "Bad regex pattern" , "Bad regex pattern" ,
155 JOptionPane.ERROR_MESSAGE );
156 } // end catch
157 } // end else
158 } // end method actionPerfomed
159 } // end annonymous inner class
160 ); // end call to addActionLister
161 } // end try
162 c atch ( ClassNotFoundException classNotFound )
163 {
164 JOptionPane.showMessageDialog( null ,
165 "Database Driver not found" , "Driver not found" ,
166 JOptionPane.ERROR_MESSAGE );
167
168 System.exit( 1 ); // terminate application
169 } // end catch
Outline
DisplayQueryResults.java
(6 of 8 )
Set filter using regularexpression
96
© 1992-2007 Pearson Education, Inc. All rights reserved.
170 catch ( SQLException sqlException )
171 {
172 JOptionPane.showMessageDialog( null , sqlException.getMessage(),
173 "Database error", JOptionPane.ERROR_MESSAGE );
174
175 // ensure database connection is closed
176 tableModel.disconnectFromDatabase();
177
178 System.exit( 1 ); // terminate application
179 } // end catch
180
181 // dispose of window when user quits applicatio n (this overrides
182 // the default of HIDE_ON_CLOSE)
183 setDefaultCloseOperation( DISPOSE_ON_CLOSE );
184
185 // ensure database connection is closed when user quits application
186 addWindowListener(
187
188 new WindowAdapter()
189 {
190 // disconnect from database and exit when window has closed
191 public void windowClosed( WindowEvent event )
192 {
193 tableModel.disconnectFromDatabase();
194 System.exit( 0 );
195 } // end method windowClosed
196 } // en d WindowAdapter inner class
197 ); // end call to addWindowListener
198 } // end DisplayQueryResults constructor
199
Outline
DisplayQueryResults.java
(7 of 8 )
Ensure that the databaseconnection is closed
Ensure that the databaseconnection is closedwhen window is closed
97
© 1992-2007 Pearson Education, Inc. All rights reserved.
200 // execute application
201 public static void main( String args[] )
202 {
203 new DisplayQueryResults();
204 } // end main
205 } // end class DisplayQueryResults
Outline
DisplayQueryResults.java
(8 of 8 )
98
© 2005 Pearson Education, Inc. All rights reserved.
25.10 RowSet Interface
• Interface RowSet– Configures the database connection automatically– Prepares query statements automatically– Provides set methods to specify the properties needed to establish
a connection– Part of the javax.sql package
• Two types of RowSet– Connected RowSet
• Connects to database once and remain connected– Disconnected RowSet
• Connects to database, executes a query and then closes connection
99
© 2005 Pearson Education, Inc. All rights reserved.
25.10 RowSet Interface (Cont.)
• Package javax.sql.rowset– JdbcRowSet
• Connected RowSet• Wrapper around a ResultSet• Scrollable and updatable by default
– CachedRowSet• Disconnected RowSet• Cache the data of ResultSet in memory• Scrollable and updatable by default• Serializable
– Can be passed between Java application• Limitation
– Amount of data that can be stored in memory is limited
100
© 1992-2007 Pearson Education, Inc. All rights reserved.
Portability Tip 25.5
A RowSet can provide scrollingcapability for drivers that do notsupport scrollable ResultSets.
101
© 1992-2007 Pearson Education, Inc. All rights reserved.
1 // Fig. 25.29: JdbcRowSetTest.java
2 // Displaying the contents of the authors table using JdbcRowSet.
3 import java.sql.ResultSetMetaData;
4 import java.sql.SQLException;
5 import javax.sql.rowset.JdbcRowSet;
6 import com.sun.rowset.JdbcRowSetImpl; // Sun's JdbcRowSet implementation
7
8 public class JdbcRowSetTest
9 {
10 // JDBC driver name and database URL
11 static final String DR IVER = "com.mysql. jdbc.Driver" ;
12 static final String DATABASE_URL = "jdbc:mysql://localhost/books" ;
13 static final String USERNAME = "jhtp7" ;
14 static final String PASSWORD = "jhtp7" ;
15
16 // constructor connects to database, queries database, processes
17 // results and displays r esults in window
18 public JdbcRowSetTest()
19 {
20 // connect to database books and query database
21 t r y
22 {
23 Class.forName( DR IVER );
24
Outline
JdbcRowSetTest.java
(1 of 3 )
102
© 1992-2007 Pearson Education, Inc. All rights reserved.
25 // specify properties of JdbcRowSet
26 JdbcRowSet rowSet = new JdbcRowSetImpl();
27 rowSet.setUrl( DATABASE_URL ); // set database URL
28 rowSet.setUsername( USERNAME ); // set username
29 rowSet.setPassword( PASSWORD ); // set password
30 rowSet.setCommand( "SELECT * FROM authors" ); // set query
31 rowSet.execute(); // execute query
32
33 // process query results
34 ResultSetMetaData metaData = rowSet.getMetaData();
35 int numberOfColumns = metaData.getColumnCount();
36 System.out.println( "Authors Table of Books Database:\n" );
37
38 // display rowset header
39 f o r ( int i = 1; i <= numberOfColumns; i++ )
40 System.out.printf( "%- 8 s\t" , metaData.getColumnName( i ) );
41 System.out.println();
42
43 // display each row
44 while ( rowSet.next() )
45 {
46 f o r ( int i = 1; i <= numberOfColumns; i++ )
47 System.out.printf( "%- 8 s\t" , rowSet.getObject( i ) );
48 System.out.println();
49 } // end whil e
50
51 // close the underlying ResultSet, Statement and Connection
52 rowSet.close();
53 } // end try
Outline
JdbcRowSetTest.java
(2 of 3 )
Use Sun’s referenceimplementation of JdbcRowSetinterface (JdbcRowSetImpl) tocreate a JdbcRowSet object
Invoke JdbcRowSet method setUrlto specify the database URLInvoke JdbcRowSet methodsetUsername to specify the usernameInvoke JdbcRowSet methodsetUsername to specify the passwordInvoke JdbcRowSet method
setCommand to specify the queryInvoke JdbcRowSet methodexecute to execute the query
103
© 1992-2007 Pearson Education, Inc. All rights reserved.
54 catch ( SQLException sqlException ) 55 { 56 sqlException.printStackTrace(); 57 System.exit( 1 ); 58 } // end catch 59 catch ( ClassNotFoundException classNotFound ) 60 { 61 classN otFound.printStackTrace(); 62 System.exit( 1 ); 63 } // end catch 64 } // end DisplayAuthors constructor 65 66 // launch the application 67 public static void main( String args[] ) 68 { 69 JdbcRowSetTest application = new JdbcRowSetTest(); 70 } // end main 71 } // end class JdbcRowSetTest Authors Table of Books Database: authorID firstName lastName 1 Harvey Deitel 2 Paul Deitel 3 Andrew Goldberg 4 David Choffnes
Outline
JdbcRowSetTest.java
(3 of 3 )
104
© 2005 Pearson Education, Inc. All rights reserved.
25.11 Java DB/Apache Derby
• As of JDK 6, Sun Microsystems now bundles theopen-source, pure Java database Java DB (theSun branded version of Apache Derby) with theJDK
• We use the embedded version of Java DB• There is also a network version that executes
similarly to the MySQL DBMS introduced earlierin the chapter
105
© 2005 Pearson Education, Inc. All rights reserved.
25.11 Java DB/Apache Derby• Java DB comes with several batch files to configure and run it• First set the environment variable JAVA_HOME to refer to the JDK’s
C:\Program Files\Java\jdk1.6.0 installation directory• Open the batch file setEmbeddedCP.bat (located in C:\Program
Files\Java\jdk1.6.0\db\frameworks\embedded\bin) in a text editor suchas Notepad
• Locate the linerem set DERBY_INSTALL=
and change it toset DERBY_INSTALL=C:\Program Files\Java\jdk1.6.0\db
• Also, comment out the line@FOR %%X in ("%DERBY_HOME%") DO SET DERBY_HOME=%%~sX
by preceding it with REM• Save your changes and close this file
106
© 2005 Pearson Education, Inc. All rights reserved.
25.11 Java DB/Apache Derby
• Change directories to C:\Program Files\Java\jdk1.6.0\db\frameworks\embedded\bin\. Then, typesetEmbeddedCP.bat and press Enter to set theenvironment variables required by Java DB.
• Embedded Java DB database must reside in the samelocation as the application that manipulates the database
– Change to the directory that contains the code for Figs.25.30–25.32
• Execute the command"C:\Program Files\Java\jdk1.6.0\db\frameworks\embedded\bin\ij"
to start the command-line tool for interacting with JavaDB. The double quotes are necessary because the pathcontains a space.
107
© 2005 Pearson Education, Inc. All rights reserved.
25.11 Java DB/Apache Derby
• At the ij> prompt typeconnect 'jdbc:derby:AddressBook;create=true; user=jhtp7;password=jhtp7';
to create the AddressBook database in the currentdirectory. This command also creates the user jhtp7 withthe password jhtp7 for accessing the database.
• To create the database table and insert sample data in thedatabase type
run 'address.sql';• To terminate the Java DB command-line tool, type
exit;
108
© 2005 Pearson Education, Inc. All rights reserved.
25.12 PreparedStatements
• PreparedStatements execute more efficientlythan Statement objects
• PreparedStatements can specify parameters
109
© 2005 Pearson Education, Inc. All rights reserved.
25.12 PreparedStatements
• PreparedStatement to locate all book titles for anauthor with a specific last name and first name, and toexecute that query for several authors:
– PreparedStatement authorBooks = connection.prepareStatement( "SELECT lastName, firstName, title " + "FROM authors INNER JOIN authorISBN " + "ON authors.authorID=authorISBN.authorID " + "INNER JOIN titles " + "ON authorISBN.isbn=titles.isbn " + "WHERE lastName = ? AND firstName = ?" );
• Question marks (?) are placeholders for values that willbe passed as part of the query to the database
110
© 2005 Pearson Education, Inc. All rights reserved.
25.12 PreparedStatements
• Program must specify the parameter values by using thePreparedStatement interface’s set methods.
• For the preceding query, both parameters are strings thatcan be set with PreparedStatement method setStringas follows:
authorBooks.setString( 1, "Deitel" );authorBooks.setString( 2, "Paul" );
• setString automatically escapes String parameter valuesas necessary (e.g., the quote in the name O’Brien)
• More info at java.sun.com/javase/6/docs/api/java/sql/PreparedStatement.html
111
© 1992-2007 Pearson Education, Inc. All rights reserved.
Performance Tip 25.2
PreparedStatements are more efficientthan Statements when executing SQLstatements multiple times and withdifferent parameter values.
112
© 1992-2007 Pearson Education, Inc. All rights reserved.
Error-Prevention Tip 25.1
Use PreparedStatements withparameters for queries that receiveString values as arguments to ensurethat the Strings are quoted properly inthe SQL statement.
113
© 1992-2007 Pearson Education, Inc. All rights reserved.
1 // Fig. 25.30: Person.java
2 // Person class that represents an entry in an address book.
3 public class Person
4 {
5 private int addressID;
6 pr ivate String firstName;
7 pr ivate String lastName;
8 pr ivate String email;
9 pr ivate String phoneNumber;
10
11 // no - argument constructor
12 public Person()
13 {
14 } // end no- argument Person constructor
15
16 // constructor
17 public Person( int id, String first, String last,
18 String emailAddress, String phone )
19 {
20 setAddressID( id );
21 setFirstName( first );
22 setLastName( last );
23 setEmail( emailAddress );
24 setPhoneNumber( phone );
25 } // end five - argument Person constructor
26
Outline
Person.java
(1 of 3 )
114
© 1992-2007 Pearson Education, Inc. All rights reserved.
27 // sets the addressID
28 public void setAddressID( int id )
29 {
30 addressID = id;
31 } // end method setAddressID
32
33 // returns the addressID
34 public int getAddressID()
35 {
36 return addressID;
37 } // end method getAddressID
38
39 // sets the firstName
40 public void setFirstName( String first )
41 {
42 firstName = first;
43 } // end method setFirstName
44
45 // returns the first name
46 public String getFirstName()
47 {
48 return firstName;
49 } // end method getFirstName
50
51 // sets the lastName
52 public void setLastName( String last )
53 {
54 lastName = last;
55 } // end method setLastName
56
Outline
Person.java
(2 of 3 )
115
© 1992-2007 Pearson Education, Inc. All rights reserved.
57 // returns the first name
58 public String getLastName()
59 {
60 return lastName;
61 } // end method getLastName
62
63 // sets the email address
64 public void setEmail( String emailAddress )
65 {
66 email = emailAddress;
67 } // end method setEmail
68
69 // returns the email address
70 public String getEmail()
71 {
72 return email;
73 } // end method getEmail
74
75 // sets the phone number
76 public void setPhoneNumber( String phone )
77 {
78 phoneNumber = phone;
79 } // end method setPhoneNumber
80
81 // returns the email address
82 public String getPhoneNumber()
83 {
84 return phoneNumber;
85 } // end method getPhoneNumber
86 } // end class Person
Outline
Person.java
(3 of 3 )
116
© 1992-2007 Pearson Education, Inc. All rights reserved.
1 // Fig. 25.31: PersonQueries.java
2 // PreparedStatements used by the Address Book application
3 import java.sql.Connection;
4 import java.sql.DriverManager;
5 import java.sql.PreparedStatement;
6 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 = "jhtp7" ;
15 p r iv ate static final String PASSWORD = "jhtp7" ;
16
17 pr ivate Connection connection = null ; // manages connection
18 pr ivate PreparedStatement selectAllPeople = null ;
19 pr ivate PreparedStatement selectPeopleByLastName = null ;
20 pr ivate PreparedStatement insertNewPerson = null ;
21
22 // constructor
23 public PersonQueries()
24 {
25 t r y
26 {
27 connection =
28 DriverManager.getConnection( URL, USERNAME, PASSWORD );
29
Outline
PersonQueries .java
(1 of 7 )
All program to usePreparedStatements
DeclarePreparedStatements
Note that we do not load theJava DB driver first. JDBC4’s automatic driverdiscovery is used here.
117
© 1992-2007 Pearson Education, Inc. All rights reserved.
30 // create query that selects all entries in the AddressBook
31 selectAllPeople =
32 connection.prepareStatement( "SELECT * FROM Addresses" );
33
34 // create query that selects entries with a specific last name
35 selectPeopleByLastName = connection.prepareStatement(
36 "SELECT * FROM Addresses WHERE LastName = ?" );
37
38 // create ins ert that adds a new entry into the database
39 insertNewPerson = connection.prepareStatement(
40 "INSERT INTO Addresses " +
41 "( FirstName, LastName, Email, PhoneNumber ) " +
42 "VALUES ( ?, ?, ?, ? )" );
43 } // end try
44 catch ( SQLException sqlException )
45 {
46 sqlException.printStackTrace();
47 System.exit( 1 );
48 } // end catch
49 } // end PersonQueries constructor
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
Outline
PersonQueries .java
(2 of 7 )
Configure eachPreparedStatement. Each ?represents a parameter.
118
© 1992-2007 Pearson Education, Inc. All rights reserved.
57 t r y
58 {
59 // executeQuery returns ResultSet containing matching entries
60 resultSet = selectAllPeople.executeQuery();
61 results = new ArrayList< Person >();
62
63 while ( resultSet.next() )
64 {
65 results.add( new Person(
66 resultSet.getInt( "address ID" ),
67 resultSet.getString( "firstName" ),
68 resultSet.getString( " lastName" ),
69 resultSet.getString( "email" ),
70 resultSet.getString( "phoneNumber" ) ) );
71 } // end while
72 } // end try
73 catch ( SQLException sqlException )
74 {
75 sqlException.print StackTrace();
76 } // end catch
77 finally
78 {
79 t r y
80 {
81 resultSet.close();
82 } // end try
Outline
PersonQueries .java
(3 of 7 )
Executes the query inPreparedStatementselectAllPeople.
Process the ResultSet.
119
© 1992-2007 Pearson Education, Inc. All rights reserved.
83 catch ( SQLException sqlException )
84 {
85 sqlException.printStackTrace();
86 close();
87 } // end catch
88 } // end finally
89
90 return results;
91 } // end method getAllPeople
92
93 // select person by last name
94
95 public List< Person > getPeopleByLastName( String name )
96 {
97 List< Person > results = null ;
98 ResultSet resultSet = null ;
99
100 t r y
101 {
102 selectPeopleByLastName.setString( 1, name ); // specify last name
103
104 // executeQuery returns ResultSet containing matching entries
105 resultSet = selectPeopleByLastName.executeQuery();
106
107 results = new ArrayList< Person >();
108
Outline
PersonQueries .java
(4 of 7 )
Specify the parameter toPreparedStatementselectPeopleByLastName.
Executes the query inPreparedStatementselectPeopleByLastName.
120
© 1992-2007 Pearson Education, Inc. All rights reserved.
109 while ( resultSet.next() )
110 {
111 results.add( new Person(
112 resultSet.getInt( "address ID" ),
113 resultSet.getString( "firs tName" ),
114 resultSet.getString( " lastName" ),
115 resultSet.getString( "email" ) ,
116 resultSet.getString( "phoneNumber" ) ) );
117 } // end while
118 } // end try
119 catch ( SQLException sqlException )
120 {
121 sqlException.printStackTrace();
122 } // end catch
123 finally
124 {
125 t r y
126 {
127 resultSet.close();
128 } // end try
129 catch ( SQLException sqlException )
130 {
131 sqlException.printStackTrace();
132 close();
133 } // end catch
134 } // end finally
135
136 return results;
137 } // end method getPeopleByName
138
Outline
PersonQueries .java
(5 of 7 )
Process the ResultSet.
121
© 1992-2007 Pearson Education, Inc. All rights reserved.
139 // add an entry
140 public int addPerson(
141 String fname, String lname, String email, String num )
142 {
143 int result = 0;
144
145 // set parameters, then execute insertNewPerson
146 t r y
147 {
148 insertNewPerson.setString( 1, fname );
149 insertNewPerson.setString( 2, lname );
150 insertNewPerson.setString( 3, email );
151 insertNewPerson.setString( 4, num );
152
153 // inser t the new entry; returns # of rows updated
154 result = insertNewPerson.executeUpdate();
155 } // end try
156 catch ( SQLException sqlException )
157 {
158 sqlException.printStackTrace();
159 close();
160 } // end catch
Outline
PersonQueries .java
(6 of 7 )
Specify the parameters toPreparedStatementinsertNewPerson.
Executes the insert operation inPreparedStatementinsertNewPerson.
122
© 1992-2007 Pearson Education, Inc. All rights reserved.
161
162 return result;
163 } // end method addPerson
164
165 // close the database connection
166 public void close()
167 {
168 t r y
169 {
170 connection.close();
171 } // end try
172 catch ( SQLException sqlException )
173 {
174 sqlException.printStackTrace();
175 } // end catch
176 } // end method close
177 } // end interface PersonQueries
Outline
PersonQueries .java
(7 of 7 )
123
© 1992-2007 Pearson Education, Inc. All rights reserved.
1 // Fig. 25.32: AddressBookDisplay.java
2 // A simple address book
3 import java.awt.event.ActionEvent;
4 import java.awt.event.ActionListener;
5 import java.awt.event.WindowAdapter;
6 import java.awt.event.WindowEvent;
7 import java.awt.Flow Layout;
8 import java.awt.GridLayout;
9 import java.util.List;
10 import javax.swing.JButton;
11 import javax.swing.Box;
12 import javax.swing.JFrame;
13 import javax.swing.JLabel;
14 import javax.swing.JPanel;
15 import javax.swing.JTextF ield;
16 import javax.swing.WindowConstants;
17 import javax.swing.BoxLayout;
18 import javax.swing.BorderFactory;
19 import javax.swing.JOptionPane;
20
21 public class AddressBookDisplay extends JFrame
22 {
23 pr ivate Person currentEnt ry ;
24 pr ivate PersonQueries personQueries;
25 pr ivate List< Person > results;
26 private int numberOfEntries = 0;
27 private int currentEntryIndex;
28
29 pr ivate JButton browseButton;
30 pr ivate JLabel emailLabel;
Outline
AddressBookDisplay.java
(1 of 14 )
124
© 1992-2007 Pearson Education, Inc. All rights reserved.
31 pr ivate JTextField emailTextField;
32 pr ivate JLabel firstNameLabel;
33 pr ivate JTextField firstNameTextField;
34 pr ivate JLabel idLabel;
35 pr ivate JTextField idTextField;
36 pr ivate JTextField indexTextField;
37 p r i va t e JLabel lastNameLabel;
38 pr ivate JTextField lastNameTextField;
39 pr ivate JTextField maxTextField;
40 pr ivate JButton nextButton;
41 pr ivate JLabel ofLabel;
42 pr ivate JLabel phoneLabel;
43 pr ivate JTextField phoneTextField ;
44 pr ivate JButton previousButton;
45 pr ivate JButton queryButton;
46 pr ivate JLabel queryLabel;
47 pr ivate JPanel queryPanel;
48 pr ivate JPanel navigatePanel;
49 pr ivate JPanel displayPanel;
50 pr ivate JTextField query TextField;
51 pr ivate JButton insertButton;
52
53 // no - argument constructor
54 public AddressBookDisplay()
55 {
56 super( "Address Book" );
57
58 // establish database connection and set up PreparedState ments
59 personQueries = new PersonQueries();
60
Outline
AddressBookDisplay.java
(2 of 14 )
125
© 1992-2007 Pearson Education, Inc. All rights reserved.
61 // create GUI
62 navigatePanel = new JPanel();
63 previousButton = new JButton();
64 indexTextField = new JTextField( 2 );
65 ofLabel = new JLabel();
66 maxTextField = new JTextField( 2 );
67 nextButton = new JButton();
68 displayPanel = new JPanel();
69 idLabel = new JLabel();
70 idTextField = new JTextField( 10 );
71 firstNameLabel = new JLabel();
72 firstNameTextField = new JTextField( 10 );
73 lastNameLabel = new JLabel();
74 lastNameTextField = new JTextField( 10 );
75 emailLabel = new JLabel();
76 emailTextField = new JTextField( 10 );
77 phoneLabel = new JLabel();
78 phoneTextField = new JTextField( 10 );
79 queryPanel = new JPan el();
80 queryLabel = new JLabel();
81 queryTextField = new JTextField( 10 );
82 queryButton = new JButton();
83 browseButton = new JButton();
84 insertButton = new JButton();
85
86 setLayout( new FlowLayout( FlowLayout.CENTER, 10, 10 ) );
87 setSize( 400, 300 );
88 setResizable( fa lse );
89
Outline
AddressBookDisplay.java
(3 of 14 )
126
© 1992-2007 Pearson Education, Inc. All rights reserved.
90 navigatePanel.setLayout(
91 new BoxLayout( navigatePanel, BoxLayout.X_AXIS ) );
92
93 previousButton.setText( "Previous" );
94 previousButton.setEnabled( fa lse );
95 previousButton.addActionListener(
96 new ActionListener()
97 {
98 public void actionPerformed( ActionEvent evt )
99 {
100 previousButtonActionPerformed( evt );
101 } // end method actionPerformed
102 } // end anonymous inner class
103 ); // end call to addActionListener
104
105 navigatePanel.add( previousButton );
106 navigatePanel.add( Box.createHorizontalStrut( 10 ) );
107
108 indexTextField.setHorizontalAlignment(
109 JTextField.CENTER );
110 indexTextField.addActionListener(
111 new ActionListener()
112 {
113 public void actionPerformed( ActionEvent evt )
114 {
115 indexTextFieldActionPerformed( evt );
116 } // end method actionPerformed
117 } // end anonymous inner class
118 ); // end call to addActionListener
119
Outline
AddressBookDisplay.java
(4 of 14 )
127
© 1992-2007 Pearson Education, Inc. All rights reserved.
120 navigatePanel.add( indexTextField );
121 navigatePanel.add( Box.createHorizontalStrut( 10 ) );
122
123 ofLabel.setText( "of" ) ;
124 navigatePanel.add( ofLabel );
125 navigatePanel.add( Box.createHorizontalStrut( 10 ) );
126
127 maxTextField.setHorizontalAlignment(
128 JTextField.CENTER );
129 maxTextField.setEditable( fa lse );
130 nav igatePanel.add( maxTextField );
131 navigatePanel.add( Box.createHorizontalStrut( 10 ) );
132
133 nextButton.setText( "Next" );
134 nextButton.setEnabled( fa lse );
135 nextButton.addActionListener(
136 new ActionListener()
137 {
138 public void actionPerformed( ActionEvent evt )
139 {
140 nextButtonActionPerformed( evt );
141 } // end method actionPerformed
142 } // end anonymous inner class
143 ); // end call to addActionListener
144
145 navigatePanel.add( nextButton );
146 add( navigatePanel );
147
148 displayPanel.setLayout( new GridLayout( 5, 2, 4, 4 ) );
Outline
AddressBookDisplay.java
(5 of 14 )
128
© 1992-2007 Pearson Education, Inc. All rights reserved.
149
150 idLabel.setText( "Address ID:" ) ;
151 displayPanel.add( idLabel );
152
153 idTextField.setEditable( fa lse );
154 displayPanel.add( idTextField );
155
156 firstNameLabel.setText( "First Name:" );
157 displayPanel.add( firstNameLabel );
158 displayPanel.add( firstNameTextField );
159
160 lastNameLabel.setText( "Last Name:" ) ;
161 displayPanel.add( lastNameLabel );
162 displayPanel.add( lastNameTextField );
163
164 emailLabel.setText( "Email:" );
165 displayPanel.add( emailLabel );
166 displayPanel.add( emailTextField );
167
168 phoneLabel.setText( "Phone Number:" );
169 displayPanel.add( phoneLabel );
170 displayPanel.add( phoneTextField );
171 add( displayPanel );
172
173 queryPanel.setLayout(
174 new BoxLayout( queryPanel, BoxLayout.X_AXIS) );
175
Outline
AddressBookDisplay.java
(6 of 14 )
129
© 1992-2007 Pearson Education, Inc. All rights reserved.
176 queryPanel.setBorder( BorderFactory.createTitledBorder(
177 "Find an entry by last name" ) );
178 queryLabel.setText( "Last Name:" );
179 queryPanel.add( Box.createHorizontalStrut( 5 ) );
180 queryPanel.add( queryLabel );
181 queryPanel.add( Box.createHorizontalStrut( 10 ) );
182 queryPanel.add( queryTextField );
183 queryPanel.add( Box.createHorizontalStrut( 10 ) );
184
185 queryButton.setText( "Find" );
186 queryButton.addActionListener(
187 new ActionListener()
188 {
189 public void actionPerformed( ActionEvent evt )
190 {
191 queryButtonActionPerformed( evt );
192 } // end method actionPerformed
193 } // end anonymous inner class
194 ); // end call to addActionListener
195
196 queryPanel.add( queryButton );
197 queryPanel.add( Box.createHorizontalStrut( 5 ) );
198 add( queryPanel );
199
Outline
AddressBookDisplay.java
(7 of 14 )
130
© 1992-2007 Pearson Education, Inc. All rights reserved.
200 browseButton.setText( "Browse All Entries" ) ;
201 browseButton.addActionListener(
202 new ActionListener()
203 {
204 public void actionPerformed( ActionEvent evt )
205 {
206 browseButtonActionPerformed( evt );
207 } // end method actionPerformed
208 } // end anonymous inner class
209 ); // end call to addActionListener
210
211 add( browseButton );
212
213 insertButton.setText( "Insert New Entry" );
214 insertButton.addActionListener(
215 new ActionListener()
216 {
217 public void actionPerformed( ActionEvent evt )
218 {
219 insertButtonActionPerformed( evt );
220 } // end method actionPerformed
221 } // end anonymous inner class
222 ); // end call to addActionListener
223
Outline
AddressBookDisplay.java
(8 of 14 )
131
© 1992-2007 Pearson Education, Inc. All rights reserved.
224 add( insertButton );
225
226 addWindowListener(
227 new WindowAdapter()
228 {
229 public void windowClosing( WindowEvent evt )
230 {
231 personQueries.close(); // close database connection
232 System.exit( 0 );
233 } // end method windowClosing
234 } // end anonymous inner class
235 ); // end call to addWindowListener
236
237 setVisible( t rue );
238 } // end no- argument constructor
239
240 // handles call when previousButton is clicked
241 private void previousButtonActionPerformed( ActionEvent evt )
242 {
243 currentEntryIndex - - ;
244
245 i f ( currentEntryIndex < 0 )
246 currentEntryIndex = numberOfEntries - 1;
247
248 indexTextField.setText( "" + ( currentEntryIndex + 1 ) );
249 indexTextFieldActionPerformed( evt );
250 } // end method previousButtonActionPerformed
251
Outline
AddressBookDisplay.java
(9 of 14 )
132
© 1992-2007 Pearson Education, Inc. All rights reserved.
252 // handles call when nextButton is clicked
253 private void nextButtonActionPerformed( ActionEvent evt )
254 {
255 currentEntryIndex++;
256
257 i f ( currentEntryIndex >= numberOfEntries )
258 currentEn tryIndex = 0;
259
260 indexTextField.setText( "" + ( currentEntryIndex + 1 ) );
261 indexTextFieldActionPerformed( evt );
262 } // end method nextButtonActionPerformed
263
264 // handles call when queryButton is clicke d
265 private void queryButtonActionPerformed( ActionEvent evt )
266 {
267 results =
268 personQueries.getPeopleByLastName( queryTextField.getText() );
269 numberO fEntries = results.size();
270
271 i f ( numberOfEntries != 0 )
272 {
273 currentEntryIndex = 0;
274 currentEntry = results.get( currentEntryIndex );
275 idTextField.setText( "" + currentEntry.getAdd ressID() );
276 firstNameTextField.setText( currentEntry.getFirstName() );
277 lastNameTextField.setText( currentEntry.getLastName() );
278 emailTextField.setText( currentEntry.getEmail() );
279 phoneTextField.se tText( currentEntry.getPhoneNumber() );
280 maxTextField.setText( "" + numberOfEntries );
Outline
AddressBookDisplay.java
(10 of 14 )
Executes the query inPreparedStatementselectPeopleByLastName fromclass PersonQueries.
133
© 1992-2007 Pearson Education, Inc. All rights reserved.
281 indexTextField.setText( "" + ( currentEntryIndex + 1 ) );
282 nextButton.setEnabled( t rue );
283 previousButton.setEnabled( t rue );
284 } // end if
285 else
286 browseButtonActionPerformed( evt );
287 } // end method queryButtonActionPerformed
288
289 // handles call when a new value is entered in indextTextField
290 private void indexTextFiel dActionPerformed( ActionEvent evt )
291 {
292 currentEntryIndex =
293 ( Integer.parseInt( indexTextField.getText() ) - 1 );
294
295 i f ( numberOfEntries != 0 && currentEntryIndex < numberOfEntries )
296 {
297 currentEntry = results.get( currentEntryIndex );
298 idTextField.setText("" + currentEntry.getAddressID() );
299 firstNameTextField.setText( currentEntry.getFirstName() );
300 lastNameTextField.setText( currentEntry.getLastName() );
301 emailTextField.setText( currentEntry.getEmail() );
302 phoneTextField.setText( currentEntry.getPhoneNumber() );
303 maxTextField.setText( "" + numberOfEntries );
304 indexTextField.setText( "" + ( currentEntryIndex + 1 ) );
305 } // end if
306 } // end method indexTextFieldActionPerformed
307
Outline
AddressBookDisplay.java
(11 of 14 )
134
© 1992-2007 Pearson Education, Inc. All rights reserved.
308 // handles call when browseButton is clicked
309 private void browseButtonActionPerformed( ActionEvent evt )
310 {
311 t r y
312 {
313 results = personQueries.getAllPeople();
314 numberOfEntries = resul ts.s ize();
315
316 i f ( numberOfEntries != 0 )
317 {
318 currentEntryIndex = 0;
319 currentEntry = results.get( currentEntryIndex );
320 idTextField.setText( "" + currentEntry.getAddr essID() );
321 firstNameTextField.setText( currentEntry.getFirstName() );
322 lastNameTextField.setText( currentEntry.getLastName() );
323 emailTextField.setText( currentEntry.getEmail() );
324 phoneT extField.setText( currentEntry.getPhoneNumber() );
325 maxTextField.setText( "" + numberOfEntries );
326 indexTextField.setText( "" + ( currentEntryIndex + 1 ) );
327 nextButton.setEnabled( t rue );
328 previousButton.setEnabled( t rue );
329 } // end if
330 } // end try
331 catch ( Exception e )
332 {
333 e.printStackTrace();
334 } // end catch
335 } // end method browseButtonActionPerformed
336
Outline
AddressBookDisplay.java
(12 of 14 )
Executes the query inPreparedStatementselectAllPeople from classPersonQueries.
135
© 1992-2007 Pearson Education, Inc. All rights reserved.
337 // handles call when insertButton is clicked
338 private void insertButtonActionPerformed( ActionEvent evt )
339 {
340 int result = personQueries.addPerson( firstNameTextField.getText(),
341 lastNameTextField.getText() , emailTextField.getText(),
342 phoneTextField.getText() );
343
344 i f ( result == 1 )
345 JOptionPane.showMessageDialog( this , "Person added!" ,
346 "Person added", JOptionPane.PLAIN_MESSAGE );
347 else
348 JOptionPane.showMessageDialog( this , "Person not added!" ,
349 "Er ror" , JOptionPane.PLAIN_MESSAGE );
350
351 browseButtonActionPerformed( evt );
352 } // end method insertButtonActionPerformed
353
354 // main method
355 public static void main( String args[] )
356 {
357 new AddressBookDisplay();
358 } // end method main
359 } // end class AddressBookDisplay
Outline
AddressBookDisplay.java
(13 of 14 )
Executes the insert operation inPreparedStatementinsertNewPerson from classPersonQueries.
136
© 1992-2007 Pearson Education, Inc. All rights reserved.
Outline
AddressBookDisplay.java
(14 of 14 )
137
© 2005 Pearson Education, Inc. All rights reserved.
25.12 Stored Procedures
• Stored procedures– Store SQL statements in a database– Invoke SQL statements by programs accessing the
database
• Interface CallableStatement– Receive arguments– Output parameters
138
© 1992-2007 Pearson Education, Inc. All rights reserved.
Portability Tip 25.6
Although the syntax for creating storedprocedures differs across databasemanagement systems, the interfaceCallableStatement provides a uniforminterface for specifying input and outputparameters for stored procedures and forinvoking stored procedures.
139
© 1992-2007 Pearson Education, Inc. All rights reserved.
Portability Tip 25.7
According to the Java API documentationfor interface CallableStatement, formaximum portability between databasesystems, programs should process the updatecounts or ResultSets returned from aCallableStatement before obtaining thevalues of any output parameters.
140
© 2005 Pearson Education, Inc. All rights reserved.
25.13 Transaction Processing
• Many applications require guarantees that aseries of database insertions, updates anddeletions executes properly before theapplications continue processing the nextdatabase operation
• Enables a program that interacts with a databaseto treat a database operation (or set ofoperations) as a single operation
– Known as an atomic operation or a transaction– At the end of a transaction, decide to commit or roll back
141
© 2005 Pearson Education, Inc. All rights reserved.
25.13 Transaction Processing
• Committing a transaction finalizes the databaseoperation(s); all insertions, updates and deletionsperformed as part of the transaction cannot bereversed without performing a new databaseoperation
• Rolling back a transaction leaves the database inits state prior to the database operation
142
© 2005 Pearson Education, Inc. All rights reserved.
25.13 Transaction Processing
• Methods of interface Connection– setAutoCommit specifies whether each SQL statement
commits after it completes (a true argument) or if severalSQL statements should be grouped as a transaction (afalse argument)
• If the argument to setAutoCommit is false, the programmust follow the last SQL statement in the transaction with acall to Connection method commit or rollback
– getAutoCommit determines the autocommit state for theConnection.