Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Microsoft SQL Server wikipedia , lookup
Extensible Storage Engine wikipedia , lookup
Concurrency control wikipedia , lookup
Microsoft Jet Database Engine wikipedia , lookup
Open Database Connectivity wikipedia , lookup
Versant Object Database wikipedia , lookup
Clusterpoint wikipedia , lookup
ContactPoint wikipedia , lookup
1 25 Accessing Databases with JDBC © 1992-2007 Pearson Education, Inc. All rights reserved. 2 OBJECTIVES In 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. © 1992-2007 Pearson Education, Inc. All rights reserved. 3 25.1 25.2 25.3 25.4 25.5 Introduction Relational Databases Relational Database Overview: The books Database SQL 25.4.1 Basic SELECT Query 25.4.2 WHERE Claus 25.4.3 ORDER BY Claus 25.4.4 Merging Data from Multiple Tables: INNER JOIN 25.4.5 INSERT Statement 25.4.6 UPDATE Statement 25.4.7 DELETE Statement Instructions for installing MySQL and MySQL Connector/J © 1992-2007 Pearson Education, Inc. All rights reserved. 4 25.6 25.7 Instructions for Setting Up a MySQL User Account Creating Database book in MySQL 25.8 Manipulating Databases with JDBC 25.8.1 Connecting to and Querying a Database 25.8.2 Querying the books Database 25.9 RowSet Interface 25.10 Java DB/Apache Derby 25.11 PreparedStatements 25.12 Stored Procedures 25.13 Transaction Processing 25.14 Wrap-Up 25.15 Web Resources and Recommended Readings © 1992-2007 Pearson Education, Inc. All rights reserved. 5 25.1 Introduction Database – Collection of data DBMS – Database management system – Storing and organizing data SQL – Relational database – Structured Query Language © 1992-2007 Pearson Education, Inc. All rights reserved. 6 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 © 1992-2007 Pearson Education, Inc. All rights reserved. 7 Software Engineering Observation 25.1 Using the JDBC API enables developers to change the underlying DBMS without modifying the Java code that accesses the database. © 1992-2007 Pearson Education, Inc. All rights reserved. 8 25.2 Relational Databases • Relational database – Table • Rows, columns – Primary key • Unique data • SQL queries – Specify which data to select from a table © 2005 Pearson Education, Inc. All rights reserved. 9 Fig. 25.1 | Employee table sample data. © 1992-2007 Pearson Education, Inc. All rights reserved. 10 Fig. 25.2 | Result of selecting distinct Department and Location data from table Employee. © 1992-2007 Pearson Education, Inc. All rights reserved. 25.3 Relational Database Overview: The books Database 11 • Sample books database – Four tables • authors – authorID, firstName, lastName • titles – isbn, title, editionNumber, copyright, publisherID, imageFile, price • authorISBN – authorID, isbn © 2005 Pearson Education, Inc. All rights reserved. 12 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. © 1992-2007 Pearson Education, Inc. All rights reserved. 13 authorID firstName lastName 1 Harvey Deitel 2 Paul Deitel 3 Andrew Goldberg 4 David Choffnes Fig. 25.4 | Sample data from the authors table. © 1992-2007 Pearson Education, Inc. All rights reserved. 25.3 Relational Database Overview: The books Database (Cont.) 14 • 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’s primary key value © 2005 Pearson Education, Inc. All rights reserved. 15 Column Description authorID The author’s ID number, a foreign key to the isbn The ISBN for a book, a foreign key to the authors table. titles table. Fig. 25.5 | authorISBN table from the books database. © 1992-2007 Pearson Education, Inc. All rights reserved. 16 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. © 1992-2007 Pearson Education, Inc. All rights reserved. 17 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 Titl e 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. © 1992-2007 Pearson Education, Inc. All rights reserved. 18 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. © 1992-2007 Pearson Education, Inc. All rights reserved. 25.3 Relational Database Overview: The books Database (Cont.) 19 • 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 © 2005 Pearson Education, Inc. All rights reserved. 20 Fig. 25.9 | Table relationships in the books database. © 1992-2007 Pearson Education, Inc. All rights reserved. 21 Common Programming Error 25.1 Not providing a value for every column in a primary key breaks the Rule of Entity Integrity and causes the DBMS to report an error. © 1992-2007 Pearson Education, Inc. All rights reserved. 22 Common Programming Error 25.2 Providing the same value for the primary key in multiple rows causes the DBMS to report an error. © 1992-2007 Pearson Education, Inc. All rights reserved. 23 Common Programming Error 25.3 Providing a foreign-key value that does not appear as a primary-key value in another table breaks the Rule of Referential Integrity and causes the DBMS to report an error. © 1992-2007 Pearson Education, Inc. All rights reserved. 24 25.4 SQL • SQL keywords – SQL queries and statements © 2005 Pearson Education, Inc. All rights reserved. 25 SQL keyword Description SELECT Retrieves data from one or more tables. FROM Tables involved in the query. Required in every 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. SELECT. Fig. 25.10 | SQL query keywords. © 1992-2007 Pearson Education, Inc. All rights reserved. 26 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 © 2005 Pearson Education, Inc. All rights reserved. 27 authorID lastName 1 Deitel 2 Deitel 3 Goldberg 4 Choffnes Fig. 25.11 | Sample authorID and lastName data from the authors table. © 1992-2007 Pearson Education, Inc. All rights reserved. 28 Software Engineering Observation 25.2 For most queries, the asterisk (*) should not be used to specify column names. In general, you process results by knowing in advance the order of the columns in the result—for example, selecting authorID and lastName from table authors ensures that the columns will appear in the result with authorID as the first column and lastName as the second column. Programs typically process result columns by specifying the column number in the result (starting from number 1 for the first column). Selecting columns by name also avoids returning unneeded columns and protects against changes in the actual order of the columns in the table(s). © 1992-2007 Pearson Education, Inc. All rights reserved. 29 Common Programming Error 25.4 If you assume that the columns are always returned in the same order from a query that uses the asterisk (*), the program may process the results incorrectly. If the column order in the table(s) changes or if additional columns are added at a later time, the order of the columns in the result would change accordingly. © 1992-2007 Pearson Education, Inc. All rights reserved. 30 25.4.2 WHERE Clause • specify the selection criteria – SELECT columnName1, columnName2, … FROM tableName WHERE criteria • SELECT title, editionNumber, copyright FROM titles WHERE copyright > 2002 © 2005 Pearson Education, Inc. All rights reserved. 31 Portability Tip 25.1 See the documentation for your database system to determine whether SQL is case sensitive on your system and to determine the syntax for SQL keywords (i.e., should they be all uppercase letters, all lowercase letters or some combination of the two?). © 1992-2007 Pearson Education, Inc. All rights reserved. 32 title editionNumber copyright Visual C# How to Program 2 2006 3 2006 Java How to Program 7 2007 C How to Program 5 2007 Visual Basic 2005 How to Program Fig. 25.12 | Sampling of titles with copyrights after 2005 from table titles. © 1992-2007 Pearson Education, Inc. All rights reserved. 33 25.4.2 WHERE Clause (Cont.) • WHERE clause condition operators – <, >, <=, >=, =, <> – LIKE • wildcard characters % and _ • SELECT authorID, firstName, lastName FROM authors WHERE lastName LIKE ‘D%’ © 2005 Pearson Education, Inc. All rights reserved. 34 authorID firstName lastName 1 Harvey Deitel 2 Paul Deitel Fig. 25.13 | Authors whose last name starts with D from the authors table. © 1992-2007 Pearson Education, Inc. All rights reserved. 35 Portability Tip 25.2 Read your database system’s documentation carefully to determine whether your system supports the LIKE operator. The SQL we discuss is supported by most RDBMSs, but it is always a good idea to check the features of SQL that are supported by your RDBMS. © 1992-2007 Pearson Education, Inc. All rights reserved. 36 25.4.2 WHERE Clause (Cont.) • SELECT authorID, firstName, lastName FROM authors WHERE lastName LIKE ‘_i%’ © 2005 Pearson Education, Inc. All rights reserved. 37 authorID firstName lastName 3 Andrew Goldberg Fig. 25.14 | The only author from the authors table whose last name contains o as the second letter. © 1992-2007 Pearson Education, Inc. All rights reserved. 38 25.4.3 ORDER BY Clause • Optional ORDER BY clause – SELECT columnName1, columnName2, … FROM tableName ORDER BY column ASC • SELECT authorID, firstName, lastName FROM authors ORDER BY lastName ASC – SELECT columnName1, columnName2, … FROM tableName ORDER BY column DESC • SELECT authorID, firstName, lastName FROM authors ORDER BY lastName DESC © 2005 Pearson Education, Inc. All rights reserved. 39 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. © 1992-2007 Pearson Education, Inc. All rights reserved. 40 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. © 1992-2007 Pearson Education, Inc. All rights reserved. 41 25.4.3 ORDER BY Clause (Cont.) • ORDER BY multiple fields – ORDER BY column1 sortingOrder, column2 sortingOrder, … • SELECT authorID, firstName, lastName FROM authors ORDER BY lastName, firstName © 2005 Pearson Education, Inc. All rights reserved. 42 authorID firstName lastName 4 David Choffnes 1 Harvey Deitel 2 Paul Deitel 4 Andrew Goldberg Fig. 25.17 | Sample data from authors in ascending order by lastName and firstName. © 1992-2007 Pearson Education, Inc. All rights reserved. 43 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 © 2005 Pearson Education, Inc. All rights reserved. 44 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 3 2006 013152539 Visual C# How to Program 2 2006 Program Fig. 25.18 | Sampling of books from table titles whose titles end with How to Program in ascending order by title. © 1992-2007 Pearson Education, Inc. All rights reserved. 25.4.4 Merging Data from Multiple Tables: INNER JOIN 45 • 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 © 2005 Pearson Education, Inc. All rights reserved. 46 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 in ascending order by lastName and firstName. © 1992-2007 Pearson Education, Inc. All rights reserved. 47 Software Engineering Observation 25.3 If a SQL statement includes columns with the same name from multiple tables, the statement must precede those column names with their table names and a dot (e.g., authors.authorID). © 1992-2007 Pearson Education, Inc. All rights reserved. 48 Common Programming Error 25.5 Failure to qualify names for columns that have the same name in two or more tables is an error. © 1992-2007 Pearson Education, Inc. All rights reserved. 49 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’ ) © 2005 Pearson Education, Inc. All rights reserved. 50 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. © 1992-2007 Pearson Education, Inc. All rights reserved. 51 Common Programming Error 25.6 It is normally an error to specify a value for an autoincrement column. © 1992-2007 Pearson Education, Inc. All rights reserved. 52 Common Programming Error 25.7 SQL uses the single-quote (') character as a delimiter for strings. To specify a string containing a single quote (e.g., O’Malley) in a SQL statement, the string must have two single quotes in the position where the single-quote character appears in the string (e.g., 'O''Malley'). The first of the two single-quote characters acts as an escape character for the second. Not escaping single-quote characters in a string that is part of a SQL statement is a SQL syntax error. © 1992-2007 Pearson Education, Inc. All rights reserved. 53 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’ © 2005 Pearson Education, Inc. All rights reserved. 54 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. © 1992-2007 Pearson Education, Inc. All rights reserved. 55 25.4.7 DELETE Statement • Remove data from a table – DELETE FROM tableName WHERE criteria • DELETE FROM authors WHERE lastName = ‘Jones’ AND firstName = ‘Sue’ © 2005 Pearson Education, Inc. All rights reserved. 56 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. © 1992-2007 Pearson Education, Inc. All rights reserved. 25.5 Instructions to Install MySQL and MySQL Connector/J 57 • Install MySQL – Platform-specific installation requirements: • dev.mysql.com/doc/refman/5.0/en/general-installationissues.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 © 2005 Pearson Education, Inc. All rights reserved. 25.5 Instructions to Install MySQL and MySQL Connector/J 58 • MySQL Server Instance Configuration Wizard – Click Next > then select Standard Configuration and click Next > again. – Not necessary to install MySQL as a Windows service for our examples • Uncheck Install as a Windows Service • Check Include Bin Directory in Windows PATH – Click Next > then click Execute to perform the server configuration. – Click Finish to close the wizard. © 2005 Pearson Education, Inc. All rights reserved. 25.5 Instructions to Install MySQL and MySQL Connector/J 59 • 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 of mysql-connector-java-5.0.4 – Docs also online at dev.mysql.com/doc/connector/j/en/ connector-j.html © 2005 Pearson Education, Inc. All rights reserved. 25.6 Instructions on Setting MySQL User Account 60 • 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; © 2005 Pearson Education, Inc. All rights reserved. 61 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; © 2005 Pearson Education, Inc. All rights reserved. 62 25.8 Manipulating Databases with JDBC • Connect to a database • Query the database • Display the results of the query in JTable © 2005 Pearson Education, Inc. All rights reserved. 25.8.1 Connecting to and Querying a Database 63 • 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 © 2005 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; Outline Imports for the JDBC classes and interfaces from package java.sql class DisplayAuthors .java (1 of 3 ) 9 10 public 64 DisplayAuthors 11 { 12 // JDBC driver name and database URL 13 static final String D R I V E R = "com.mysql.jdbc.Driver" ; 14 static St ring D A T A B A S E _ U R=L " j d b c : m y s q l : / / l o c a l h o s t / b o o k s " ; final 15 16 // launch the application 17 public 18 static v o i d main( String args[] ) Declare a String constant that specifies the database URL { 19 Connection connection = 20 Statement statement = null ; // query statement 21 ResultSet resultSet = null ; // manages results Declare a String constant that specifies the JDBC driver’s class name null ; // manages connection 22 // connect to database books and query database 23 try 24 25 { 26 // load the driver class 27 Class.forName( 28 D R I V E R ); Loads the class definition for the database driver. © 1992-2007 Pearson Education, Inc. All rights reserved. 29 // establish connection to database 30 connection = DriverManager.getConnection( 31 D A T A B A S E _ U,R L"jhtp7" , "jhtp7" ); 32 33 // create Statement for querying database 34 statement 65 connection.createStatement(); Invokes ConnectionDisplayAuthors method .java createStatement to obtain an object // query database Use theinterface Statement (2 of 3Statement. ) object’s that implements resultSet = statement.executeQuery( executeQuery method to "SELECT authorID, firstName, lastName FROM authors" ); execute a query that selects all the author information // process query results Obtains the metadata ResultSetMetaData metaData = resultSet.getMetaData(); from table authors. Uses ResultSetMetaData for the ResultSet. int numberOfColumns = metaData.getColumnCoun t(); method getColumnCount System.out.println( "Authors Table of Books Database:\n" ); to retrieve the number of f o r ( int i = 1; i <= numberOfColumns; i++ ) columns in the ResultSet. Obtain column System.out.printf( " %- 8 s\t " , metaData.getColumnName( i ) ); name using method System. out.println(); getColumnName Position the ResultSet cursor to the first while ( resultSet.next() ) row in the ResultSet with method next { 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 f o r ( int i = 51 1; i <= numberOfColumns; i++ ) System.out.printf( 52 System.out.p 53 } 54 55 = Initialize a Outline Connection reference called connection. } // end while rintln(); " %- 8 s\t " , resultSet.getObject( i ) ); Extract the contents of one column in the current row // end try © 1992-2007 Pearson Education, Inc. All rights reserved. c a t c h ( SQLException 56 sqlException ) sqlException.printStackTrace(); 58 } 59 // end catch c a t c h ( ClassNotFoundException 60 classNotFound.printStackTrace(); 62 } 63 // end catch 64 finally 65 { 66 try 67 { // ensure resultSet, statement and connection 68 resultSet.close(); 69 statement.close(); 70 connection.close(); 71 } // end try 72 c a t c h ( Exception exception ) 73 { 66 classNotFound ) { 61 DisplayAuthors .java ClassNotFoundException is thrown if the class loader (3 of 3 ) arecannot closed locate the driver class Close the Statement and the database Connection. exception.printStackTrace(); 74 } // end catch 75 } // end finally 76 77 Catch SQLException, which is Outline thrown if the query execution or ResultSet process fails { 57 } // end main 78 } // end class DisplayAuthors Authors Table of Books Database: authorID 1 2 3 4 firstName Harvey Paul Andrew David lastName Deitel Deitel Goldberg Choffnes © 1992-2007 Pearson Education, Inc. All rights reserved. 67 Software Engineering Observation 25.4 Most major database vendors provide their own JDBC database drivers, and many third-party vendors provide JDBC drivers as well. For more information on JDBC drivers, visit the Sun Microsystems JDBC Web site, servlet.java.sun.com/products/ jdbc/drivers. © 1992-2007 Pearson Education, Inc. All rights reserved. 68 Software Engineering Observation 25.5 Most database management systems require the user to log in before accessing the database contents. DriverManager method getConnection is overloaded with versions that enable the program to supply the user name and password to gain access. © 1992-2007 Pearson Education, Inc. All rights reserved. 69 RDBMS Database URL format MySQL jdbc:mysql:// ORACLE jdbc:oracle:thin:@ DB2 jdbc:db2: hostname : portNumber /databaseName Java DB/Apache Derby jdbc:derby: dataBaseName (embedded) ! hostname : portNumber /databaseName hostname : portNumber : databaseName jdbc:derb y:// hostname : portNumber /databaseName (network) ! Microsoft SQL Server jdbc:sqlserver:// Sybase jdbc:sybase:Tds: hostname : portNumber ; databaseName=dataBaseName hostname : portNumber /databaseName Fig. 25.24 | Popular JDBC database URL formats. © 1992-2007 Pearson Education, Inc. All rights reserved. 70 Software Engineering Observation 25.6 Metadata enables programs to process ResultSet contents dynamically when detailed information about the ResultSet is not known in advance. © 1992-2007 Pearson Education, Inc. All rights reserved. 71 Common Programming Error 25.8 Initially, a ResultSet cursor is positioned before the first row. Attempting to access a ResultSet’s contents before positioning the ResultSet cursor to the first row with method next causes a SQLException. © 1992-2007 Pearson Education, Inc. All rights reserved. 72 Performance Tip 25.1 If a query specifies the exact columns to select from the database, the ResultSet contains the columns in the specified order. In this case, using the column number to obtain the column’s value is more efficient than using the column name. The column number provides direct access to the specified column. Using the column name requires a search of the column names to locate the appropriate column. © 1992-2007 Pearson Education, Inc. All rights reserved. 73 Common Programming Error 25.9 Specifying column number 0 when obtaining values from a ResultSet causes a SQLException. © 1992-2007 Pearson Education, Inc. All rights reserved. 74 Common Programming Error 25.10 Attempting to manipulate a ResultSet after closing the Statement that created the ResultSet causes a SQLException. The program discards the ResultSet when the corresponding Statement is closed. © 1992-2007 Pearson Education, Inc. All rights reserved. 75 Software Engineering Observation 25.7 Each Statement object can open only one ResultSet object at a time. When a Statement returns a new ResultSet, the Statement closes the prior ResultSet. To use multiple ResultSets in parallel, separate Statement objects must return the ResultSets. © 1992-2007 Pearson Education, Inc. All rights reserved. 76 25.8.2 Querying the books Database • Allow the user to enter any query into the program • Display the results of a query in a JTable © 2005 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 i m p o r t java.sql.Re s u l t S e t M e t a D a t a ; 8 import java.sql.SQLException; 9 import javax.swing.table.AbstractTableModel; Outline 77 ResultSetTable Model.java (1 of 7 ) 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 e x t e n d s AbstractTableModel 18 { 19 private Connection connection; 20 private Statement statement; 21 private ResultSet resultSet; 22 private ResultSetMetaData 23 private int numberOfRows; metaData; Class ResultSetTableModel extends class AbstractTableModel, which implements interface TableModel. 24 25 // keep track of database connection status 26 p r i v a t e b o o l e a n connectedToDatabase = f a l s e ; 27 Instance variable keeps track of database connection status © 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 Establishes a connection ClassNotFoundException to the database. String password, String query ) 31 t h r o ws 32 33 ResultSetTableModel( String driver, String url, String username, Constructor SQLException, { 34 Class.forName( driver ); 35 // connect to database accepts five String arguments—the driver class name, the database URL, the ResultSetTable username, the password and the Model.java default query to perform connection = DriverManager.getConnection( url, username, password ); 36 37 38 // create Statement to query database 39 statement = connection.createStatement( 40 ResultSet.TYPE_SCROLL_INSENSITIVE , 41 ResultSet.CONCUR_READ_ONLY ); Outline 78 (2 of 7 ) Invokes Connection method createStatement to create a Statement object. 42 43 // update database connection status 44 connectedToDatabase = t r u e; 45 46 // set query and execute it 47 setQuery( query ); 48 49 } // end constructor Indicate that connect to database is successful Invokes ResultSetTableModel method setQuery to perform ResultSetTableModel the default query. © 1992-2007 Pearson Education, Inc. All rights reserved. 50 // get class that represents column type 51 public 52 Class getColumnClass( int column ) t h r o w s IllegalStateException Outline { 53 // ensure database connection is available 54 if ( !connectedToDatabase ) t h r o w n e w IllegalStateException( 55 56 57 // determine Java class of column 58 try Verify database Override method getColumnClass to obtain a connection status "Not Connected to Database" ); Class object that representsResultSetTable the superclass of Model.java all objects in a particular column { 59 String 60 className = 79 metaData.getColumnClassName(column (3 of 7 ) class Obtains the fully qualified +name 1 ); for the specified column. 61 62 // return Class object that represents className 63 r e t u r n Class.forName( className ); } 64 Loads the class definition for the class and returns the corresponding Class object. // end try c a t c h ( Exception exception ) 65 { 66 excepti 67 } 68 on.printStackTrace(); // end catch 69 r e t u r n Object. c l a s s ; // if problems occur above, assume type Object 70 71 } // end method getColumnClass Returns the default type. 72 73 // get number of columns in ResultSet 74 public 75 int getColu mnCount() t h r o w s IllegalStateException { 76 // ensure database connection is available 77 if 78 79 ( !connectedToDatabase ) t h r o w n e w IllegalStateException( Override methodtogetColumnCount to "Not Connected Database" ) ; obtain the number of columns in the model’s underlying ResultSet © 1992-2007 Pearson Education, Inc. All rights reserved. 80 // determine number of columns 81 try { 82 return 83 } 84 Obtains the number of columns in the ResultSet. metaData.getColumnCount(); // end try c a t c h ( SQLException sqlException ) 85 ResultSetTable Model.java { 86 sqlException.printStackTrace(); 87 } 88 // end catch (4 of 7 ) 89 r e t u r n 0; // if problems occur above, return 0 for number of columns 90 91 Outline 80 } // end method getColumnCount 92 93 // get name of a particular column in ResultSet 94 public 95 String getColumnName( int co lumn ) t h r o w s IllegalStateException { 96 // ensure database connection is available 97 if ( !connectedToDatabase ) t h r o w n e w IllegalStateException( 98 99 // determine col 100 try 101 102 return } // end try Obtains the column name from the ResultSet. { sqlException.printStackTrace(); 107 108 metaData.getColumnName( column +1 ); c a t c h ( SQLException sqlException ) 105 106 to obtain the name of the column in the model’s underlying ResultSet { 103 104 umn name method getColumnName "NotOverride Connected to Database" ); } // end catch 109 © 1992-2007 Pearson Education, Inc. All rights reserved. r e t u r n "" ; // if problems, return empty string for column name 110 111 } // end method getColumnName Outline 112 113 // return number of rows in ResultSet 114 public 115 int getRowCount() t h r o w s IllegalStateException { if 117 ( !connectedToDatabase ) Override method getColumnCount t h r o w n e w IllegalStateException( "Not Connected to Database" ) ;to 118 obtain the number of rows in the model’s underlying ResultSet 119 return 120 121 ResultSetTable Model.java // ensure database connection is available 116 } 81 numberOfRows; (5 of 7 ) // end method getRowCount 122 123 // obtain value in particular row and column 124 public int row, int column ) t h r o w s IllegalStateException 125 126 Object getValueAt( { // ensure database connectionOverride is available method 127 if 128 getValueAt to obtain the Object in a particular row and column of the IllegalStateException( "Not Connected to Database" ); model’s underlying ResultSet ( !connectedToDatabase ) throw new 129 130 131 // obtain a value at specified ResultSet row and column 132 try 133 { 134 resultSet.absolute( row + 1 ); 135 r e t u r n resu ltSet.getObject( column + 1 ); 136 } Uses ResultSet method absolute to position the ResultSet cursor at a specific row. // end try Uses ResultSet method getObject to obtain the Object in a specific column of the current row. © 1992-2007 Pearson Education, Inc. All rights reserved. c a t c h ( SQLException sqlException ) 137 { 138 Outline sqlException.printStackTrace(); 139 } 140 82 // end catch 141 r e t u r n "" ; // if problems, return empty string object 142 143 } ResultSetTable Model.java // end method getValueAt 144 145 // set new database query string 146 public t h r o w s SQLException, IllegalStateException 147 148 (6 of 7 ) v o i d setQuery( String query ) { 149 // ensure database connection is available 150 if ( !connectedToDatabase ) t h r o w n e w IllegalStateException( 151 "Not Connected to Database" ); 152 // specify query and execute it 153 Executes the query to obtain a new ResultSet. resultSet = statement.executeQuery( query ); 154 155 // obtain meta data for ResultSet 156 met aData 157 = resultSet.getMetaData(); 158 159 // determine number of rows in ResultSet 160 resultSet.last(); // move to last row numberOfRows = resultSet.getRow(); 161 Uses ResultSet method last to position the ResultSet cursor at the last row in the ResultSet. // get row number 162 163 // notify JTable 164 fireTableStructureChanged(); 165 166 } that model has changed // end method setQuery Uses ResultSet method getRow Invokes methodthe fireTableAStructureChanged to obtain row number for the to notify any row JTable using this current in the ResultSet. ResultSetTableModel object as its model that the structure of the model hasEducation, changed.Inc. All rights reserved. © 1992-2007 Pearson 167 // close Statement and Connection 168 public 169 { 170 if 171 { v o i d disconnectFromDatabase() Verify whether the connection is already terminated Method disconnectFromDatabase Statement and Connection implement an appropriate termination method for class ResultSetTableModel ( connectedToDatabase ) 172 // close 173 try 174 { 175 r e s u l t S et.close(); 176 statement.close(); 177 connection.close(); } // end try 179 c a t c h ( SQLException s qlException ) 180 { sqlException.printStackTrace(); 181 182 } // end catch 183 finally 184 { 186 187 ResultSetTable Model.java Close the Statement and Connection if a7 ) (7 of ResultSetTableModel object is garbage collected. 178 185 Outline 83 // update database connection connectedToDatabase = false ; } // end finally } // end if 188 } // end method disconnectFromDatabase 189 } // end class ResultSetTableModel status Set connectedToDatabase to false to ensure that clients do not use an instance of ResultSetTableModel after that instance has already been terminated © 1992-2007 Pearson Education, Inc. All rights reserved. 84 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. © 1992-2007 Pearson Education, Inc. All rights reserved. 85 Portability Tip 25.3 Some JDBC drivers do not support scrollable ResultSets. In such cases, the driver typically returns a ResultSet in which the cursor can move only forward. For more information, see your database driver documentation. © 1992-2007 Pearson Education, Inc. All rights reserved. 86 Portability Tip 25.4 Some JDBC drivers do not support updatable ResultSets. In such cases, the driver typically returns a read-only ResultSet. For more information, see your database driver documentation. © 1992-2007 Pearson Education, Inc. All rights reserved. 87 Common Programming Error 25.11 Attempting to update a ResultSet when the database driver does not support updatable ResultSets causes SQLFeatureNotSupportedExceptions. © 1992-2007 Pearson Education, Inc. All rights reserved. 88 Common Programming Error 25.12 Attempting to move the cursor backward through a ResultSet when the database driver does not support backward scrolling causes a SQLException. © 1992-2007 Pearson Education, Inc. All rights reserved. 89 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. © 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. W i n d o w A d a p t e r ; 7 import java.awt.event.WindowEvent; 8 import java.sql.SQLException; 9 import java.util.regex.PatternSyntaxException; 10 i m p o r t javax.swing.JFrame; 11 i m p o r t javax.swing.JTextArea; 12 i m p o r t javax.swing.JScrollPane; Outline 90 DisplayQuery Results.java (1 of 8 ) 13 i m p o r t j a v a x . s w i n g . S c r o l l P a n e C o n s t a n t s ; 14 i m p o r t javax.swing.JTable; 15 i m p o r t javax.swing.JOptionPane; 16 i m p o r t javax.swing.JButton; 17 i m p o r t javax.swing.Box; 18 i m p o r t javax.swing.JLabel; 19 i m p o r t javax.swing.JTextField; 20 i m p o r t javax.swing.R owFilter; 21 i m p o r t javax.swing.table.TableRowSorter; 22 i m p o r t javax.swing.table.TableModel; 23 24 public class DisplayQueryResults e x t e n d s JFrame 25 { 26 // JDBC database URL, username and password 27 static final Str ing D R I V E R = "com.mysql.jdbc.Driver" ; 28 static final String D A T A B A S E _ U R=L " j d b c : m y s q l : / / l o c a l h o s t / b o o k s " ; 29 static final String USERNAME = "jhtp7" ; 30 static final String PASSWORD= "jhtp7" ; Declare the database driver class name, database URL, username and password for accessing the database © 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 private ResultSetTableModel 36 private JTextArea queryArea; 37 // cr eate ResultSetTableModel and GUI 39 public 40 Results.java DisplayQueryResults() (2 of 8 ) { s u p e r( "Displaying Query Results" 41 Declare the default query Declare tableModel to be a reference to ResultSetTableModel DisplayQuery tableModel; 38 Outline 91 ); 42 // create ResultSetTableModel and display database table 43 try 44 45 { 46 // create TableModel for results of query SELECT * FROM authors 47 tableModel = 48 n e w ResultSetTableModel( D R I V E R, D A T A B A S E _ U,R L U S E R N A M, E P A S S W O R, DDEFAULT_QUERY ); 49 50 // set up JText 51 queryArea = 52 53 Area in which user types queries n e w JTextArea( queryArea.setWrapStyleWord( queryArea.setLineWrap( Create TableModel for results of default query “SELECT * FROM authors” DEFAULT_QUERY , 3, 100 ); t r u e ); t r u e ); 54 55 JScrollPane scrollPane = n e w JScr ollPane( queryArea, 56 ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED , 57 ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER ); 58 59 60 // set up JButton for submitting queries JButton submitBut ton = n e w JButton( "Submit Query" ); © 1992-2007 Pearson Education, Inc. All rights reserved. 61 62 63 64 // create Box to manage placement of queryArea and Outline // submitButton in GUI Box boxNorth = Box.createHorizontalBox(); 65 boxNorth.add( scrollPane ); 66 boxNorth.add( submitButton ); DisplayQuery Results.java 67 68 // create JTable delegate for tableModel 69 JTable resultTable = Create JTable delegate for tableModel (3 of 8 ) n e w JTable( tableModel ); 70 71 72 73 74 92 JLabel filterLabel = final n e w JLabel( JTextField filterText = JButton filterButton = "Filter:" ); n e w JTextField( ) ; n e w JButton( "Apply Filter" ); Box boxSouth = boxNorth.createHorizontalBox(); 75 76 boxSouth.add( filterLabel ); 77 boxSouth.add( filterText ); 78 boxSouth.a dd( filterButton ); 79 80 81 82 83 // place GUI components on content pane add( boxNorth, add( B o r d e r L a y o u t . N O R T H); n e w JScrollPane( resultTable ), add( boxSouth, B o r d e r L a y o u t . C E N T E R ); B o r d e r L a y o u t .S O U T H); 84 85 // create event listener for submitButton 86 submitButton.addActionListener( 87 © 1992-2007 Pearson Education, Inc. All rights reserved. n e w ActionListener() 88 89 // pass query to table model 90 public void 91 92 // perform a new query { tableModel.setQuery( 96 } queryArea.getText() ); (4 of 8 ) // end try c a t c h ( SQLException sqlException ) 98 99 DisplayQuery Results.java try 94 97 actionPerformed( ActionEvent event ) 93 { 93 95 Register an event handler for the submitButton thatOutline the user clicks to submit a query to the database { { JOptionPane.showMessageDialog( 100 sqlException.getMessage(), 101 null , "Database Invoke ResultSetTableModel method setQuery to execute error", the new query JOptionPane.ERROR_MESSAGE ); 102 103 104 // try to recover from inv 105 // by executing default query try 106 107 { tableModel.setQuery( 108 queryArea.setText( 109 110 } DEFAULT_QUERY ); D E F AUL T _QUERY); // end try c a t c h ( SQLException sqlException2 ) 111 112 alid user query { 113 JOptionPane.showMessageDialog( null , 114 sqlExcep "Database 115 tion2.getMessage(), error", JOptionPane.ERROR_MESSAGE ); 116 © 1992-2007 Pearson Education, Inc. All rights reserved. 117 // ensure database connection is closed 118 tableModel.disconnectFromDatabase(); 119 System.exit( 120 } 121 125 DisplayQuery Results.java // end actionPerformed } 124 // terminate application // end outer catch } 123 // end ActionListener inner class ); // end call to addActionListener (5 of 8 ) 126 127 final 129 TableRowSorter< TableModel > sorter = n e w TableRowSorter< TableModel >( tableModel ); 128 94 // end inner catch } 122 1 ); Ensure that the database connection is Outline closed Set up TableRowSorter resultTable.setRowSorter( sorter ); 130 setSize( 500, 250 ); 131 setVisible( t r u e ); // set window si z e // display window 132 133 134 // create listener for filterButton filterButton.addActionListener( n e w ActionListener() 135 136 { // pass filter text to listener 137 public void 138 139 actionPerformed( ActionEvent e ) { String text = filterText.getText(); 140 141 if 142 sorter.setRowFilter( 143 146 0 ) null ); No filter initially else 144 145 ( text.length() == { try © 1992-2007 Pearson Education, Inc. All rights reserved. { 147 sorter.setRowFilter( 148 Outline Set filter using regular expression RowFilter.regexFilter( text ) ); 149 } 150 // end try c a t c h ( PatternSyntaxExceptio n pse ) 151 { 152 JOptionPane.showMessageDialog( 153 null , 154 "Bad regex pattern" , "Bad regex pattern" , 155 JOptionPane.ERROR_MESSAGE ); } 156 } 157 } 158 } 159 ); 160 161 } DisplayQuery Results.java (6 of 8 ) // end catch // end else // end method actionPerfomed // end annonymous inner class // end call to addActionLister // end try c at c h ( ClassNotFoundException classNotFound ) 162 163 95 { JOptionPane.showMessageDialog( 164 null , 165 "Database Driver not found" , "Driver not found" , 166 JOptionPane.ERROR_MESSAGE ); 167 System.exit( 168 169 } 1 ); // terminate application // end catch © 1992-2007 Pearson Education, Inc. All rights reserved. c a t c h ( SQLException sqlException ) 170 { 171 JOptionPane.showMessageDialog( 172 "Database 173 null , sqlException.getMessage(), Outline 96 error", JOptionPane.ERROR_MESSAGE ); 174 175 // ensure database connection is closed 176 tableModel.disconnectFromDatabase(); 177 System.exit( 178 } 179 1 ); Ensure that the database connection is closed // terminate application DisplayQuery Results.java (7 of 8 ) // end catch 180 181 // dispose of window when user quits applicatio 182 // the default of HIDE_ON_CLOSE) 183 setDefaultCloseOperation( n (this overrides D I S P O S E _ O N _ C L O S);E 184 185 // ensure database connection is closed when user quits application 186 addWindowListener( 187 n e w WindowAdapter() 188 { 189 190 // disconnect from database and exit when window has closed 191 public void 192 { windowClosed( WindowEvent event ) 193 tableModel.disconnectFromDatabase(); 194 System.exit( 195 196 } ); 197 198 } 0 ); } // end method windowClosed // en d WindowAdapter inner class Ensure that the database connection is closed when window is closed // end call to addWindowListener // end DisplayQueryResults constructor 199 © 1992-2007 Pearson Education, Inc. All rights reserved. 200 // execute application 201 public static void 202 { Outline 97 n e w DisplayQueryResults(); 203 204 main( String args[] ) } // end main 205 } // end class DisplayQueryResults DisplayQuery Results.java (8 of 8 ) © 1992-2007 Pearson Education, Inc. All rights reserved. 98 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 © 2005 Pearson Education, Inc. All rights reserved. 99 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 • • • • © 2005 Pearson Education, Inc. All rights reserved. 100 Portability Tip 25.5 A RowSet can provide scrolling capability for drivers that do not support scrollable ResultSets. © 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 i m p o r t javax.sql.rowset.JdbcRowSet; 6 import com.sun.rowset.JdbcRowSetImpl; // Sun's JdbcRowSet implementation 7 8 public class 9 { 10 JdbcRowSetTest Outline 101 JdbcRowSetTest .java (1 of 3 ) // JDBC driver name and database URL 11 static final String D R I V E R = "com.mysql.jdbc.Driver" ; 12 static final String D A TA B A S E _ U R L = "jdbc:mysql://localhost/books" ; 13 static final String U S E R N A M E= "jhtp7" ; 14 static final String PASSWORD = "jhtp7" ; 15 // constructor connects to database, queries database, processes 16 17 // results and displays r 18 public 19 // connect to database books and query database try 21 23 JdbcRowSetTest() { 20 22 esults in window { Class.forName( D R I V E R ); 24 © 1992-2007 Pearson Education, Inc. All rights reserved. 25 // specify properties of JdbcRowSet 26 JdbcRowSet rowSet = n e w JdbcRowSetImpl(); Use Sun’s reference Outline Invoke JdbcRowSet method setUrl rowSet.setUrl( D A T A B A S E _ U R);L // set database URL implementation of JdbcRowSet Invoke JdbcRowSet method to specify the database URL rowSet.setUsername( U S E RN A M E); // set username interface (JdbcRowSetImpl) to Invoke JdbcRowSet method setUsername to specify the username rowSet.setPassword( P A S S W O R ); D // set password JdbcRowSet method createInvoke a JdbcRowSet object rowSet.setCommand( "SELECT * FROM authors" setUsername ); // set queryto specify the password setCommand to JdbcRowSetTest specify the query Invoke JdbcRowSet method rowSet.execute(); // execute query execute to execute the query.java 27 28 29 30 31 32 // process query results 33 34 ResultSetMetaData 35 int metaData numberOfColumns System.out.println( 36 = = rowSet.getMetaData(); 102 (2 of 3 ) metaData.getColumnCount(); "Authors Table of Books Database:\n" ); 37 // display rowset header 38 f o r ( int i = 39 1; i <= numberOfColumns; i++ ) 40 System.out.printf( 41 System.out.println(); " %- 8 s\t " , metaData.getColumnName( i ) ); 42 // display each row 43 while 44 ( rowSet.next() ) { 45 f o r ( int i = 46 1; i <= numberOfColumns; i++ ) 47 System.out.printf( 48 System.out.println(); } 49 " %- 8 s\t " , rowSet.getObject( i ) ); // end whil e 50 51 // close the underlying ResultSet, Statement and Connection 52 rowSet.close(); 53 } // end try © 1992-2007 Pearson Education, Inc. All rights reserved. c a t c h ( SQLException sqlException ) 54 { 55 sqlException.printStackTrace(); 56 System.exit( 57 } 58 // end catch { 60 61 classN 62 System.exit( } 63 64 1 ); c a t c h ( ClassNotFoundException classNotFound ) 59 } Outline 103 otFound.printStackTrace(); 1 ); JdbcRowSetTest .java (3 of 3 ) // end catch // end DisplayAuthors constructor 65 66 // launch the application 67 public static void 68 args[] ) { JdbcRowSetTest application = 69 70 main( String } n e w JdbcRowSetTest(); // end main 71 } // end class JdbcRowSetTest Authors Table of Books Database: authorID 1 2 3 4 firstName Harvey Paul Andrew David lastName Deitel Deitel Goldberg Choffnes © 1992-2007 Pearson Education, Inc. All rights reserved. 104 25.11 Java DB/Apache Derby • As of JDK 6, Sun Microsystems now bundles the open-source, pure Java database Java DB (the Sun branded version of Apache Derby) with the JDK • We use the embedded version of Java DB • There is also a network version that executes similarly to the MySQL DBMS introduced earlier in the chapter © 2005 Pearson Education, Inc. All rights reserved. 105 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 such as Notepad • Locate the line rem set DERBY_INSTALL= and change it to set 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 © 2005 Pearson Education, Inc. All rights reserved. 106 25.11 Java DB/Apache Derby • Change directories to C:\Program Files\Java\ jdk1.6.0\db\frameworks\embedded\bin\. Then, type setEmbeddedCP.bat and press Enter to set the environment variables required by Java DB. • Embedded Java DB database must reside in the same location 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 Java DB. The double quotes are necessary because the path contains a space. © 2005 Pearson Education, Inc. All rights reserved. 107 25.11 Java DB/Apache Derby • At the ij> prompt type connect 'jdbc:derby:AddressBook;create=true; user=jhtp7;password=jhtp7'; to create the AddressBook database in the current directory. This command also creates the user jhtp7 with the password jhtp7 for accessing the database. • To create the database table and insert sample data in the database type run 'address.sql'; • To terminate the Java DB command-line tool, type exit; © 2005 Pearson Education, Inc. All rights reserved. 108 25.12 PreparedStatements • PreparedStatements execute more efficiently than Statement objects • PreparedStatements can specify parameters © 2005 Pearson Education, Inc. All rights reserved. 109 25.12 PreparedStatements • PreparedStatement to locate all book titles for an author with a specific last name and first name, and to execute 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 will be passed as part of the query to the database © 2005 Pearson Education, Inc. All rights reserved. 110 25.12 PreparedStatements • Program must specify the parameter values by using the PreparedStatement interface’s set methods. • For the preceding query, both parameters are strings that can be set with PreparedStatement method setString as follows: authorBooks.setString( 1, "Deitel" ); authorBooks.setString( 2, "Paul" ); • setString automatically escapes String parameter values as necessary (e.g., the quote in the name O’Brien) • More info at java.sun.com/javase/6/docs/api/ java/sql/PreparedStatement.html © 2005 Pearson Education, Inc. All rights reserved. 111 Performance Tip 25.2 PreparedStatements are more efficient than Statements when executing SQL statements multiple times and with different parameter values. © 1992-2007 Pearson Education, Inc. All rights reserved. 112 Error-Prevention Tip 25.1 Use PreparedStatements with parameters for queries that receive String values as arguments to ensure that the Strings are quoted properly in the SQL statement. © 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 4 { Person 5 private int 6 private String firstName; 7 private String lastName; 8 private String email; 9 private String phoneNumber; Outline 113 addressID; Person.java (1 of 3 ) 10 11 12 // no - argument public 13 { 14 } constructor Person() // end no- argument Person constructor 15 16 // constructor 17 public String 18 19 Person( int id, String first, String last, emailAddress, String phone ) { 20 setAddressID( id ); 21 setFirstName( first ); 22 setLastName( last ); 23 setEmail( emailAddress ); 24 setPhoneNumber( phone ); 25 } // end five - argument Person constructor 26 © 1992-2007 Pearson Education, Inc. All rights reserved. 27 // sets the addressID 28 public void 29 int id ) { } // end method setAddressID 32 33 // returns the addressID 34 public int 35 getAddressID() { return 36 37 Outline 114 addressID = id; 30 31 setAddressID( } Person.java (2 of 3 ) addressID; // end method getAddressID 38 39 // sets the firstName 40 public void 41 { firstName = first; 42 43 setFirstName( String first ) } // end method setFirstName 44 45 // returns the first name 46 public 47 { return 48 49 String getFirstName() } firstName; // end method getFirstName 50 51 // sets the lastName 52 public void 53 { lastName = last; 54 55 setLastName( String last ) } // end method setLastName 56 © 1992-2007 Pearson Education, Inc. All rights reserved. 57 // returns the first name 58 public 59 { return 60 61 String getLastName() } lastName; // end method getLastName 62 63 // sets the email address 64 public void 65 setEmail( String emailAddress ) { Person.java (3 of 3 ) email = emailAddress; 66 67 Outline 115 } // end method setEmail 68 69 // returns the email address 70 public 71 { r e t u r n email; 72 73 String getEmail() } // end method getEmail 74 75 // sets the phone number 76 public void 77 { phoneNumber = phone; 78 79 setPhoneNumber( String phone ) } // end method setPhoneNumber 80 81 // returns the email address 82 public 83 { return 84 85 String getPhoneNumber() } phoneNumber; // end method getPhoneNumber 86 } // end class Person © 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 i m p o r t java.sql .SQLException; 8 i m p o r t java.util.List; 9 import Outline All program to use PreparedStatements 116 PersonQueries .java (1 of 7 ) java.util.ArrayList; 10 11 public class PersonQueries 12 { 13 private static final String U R L = " j d b c : d e r b y : A d d r e s s B o o k "; 14 private static final String USERNAME = "jhtp7" ; 15 p r i v ate static final String P A S S W O R= D "jhtp7" ; 16 17 p r i v a t e Connection connection = null ; // manages connection 18 private PreparedStatement selectAllPeople = 19 private PreparedStatement selectPeopleByLastName = null ; 20 private PreparedStatement insertNewPerson = null ; null ; Declare PreparedStatements 21 22 // constructor 23 public 24 { try 25 26 27 28 29 PersonQueries() { Note that we do not load the Java DB driver first. JDBC connection = 4’s automatic DriverManager.getConnection( U R L, driver U S E R N A M, E P A S S W ODR ); discovery is used here. © 1992-2007 Pearson Education, Inc. All rights reserved. 30 // create query that selects all entries in the AddressBook 31 selectAllPeople = connection.prepareStatement( 32 "SELECT * FROM Addresses"); Outline 117 33 34 // create query that selects entries with a specific last name 35 selectPeopleByLastName = connection.prepareStatement( 36 "SELECT * FROM Addresses WHERE LastName = ?" ); PersonQueries .java 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 c a t c h ( SQLException sqlException ) 44 Configure each PreparedStatement. Each ? represents a parameter. { 45 sqlException.printStackTrace(); 46 System.exit( 47 } 48 49 ); + (2 of 7 ) } 1 ); // end catch // end PersonQueries constructor 50 51 // select all of the addresses in the database 52 public 53 List< Person > getAllPeople() { 54 List< Person > results = 55 ResultSet resultSet = null ; null ; 56 © 1992-2007 Pearson Education, Inc. All rights reserved. try 57 58 { 59 // executeQuery returns ResultSet containing matching entries 60 resultSet = selectAllPeople.executeQuery(); results = 61 n e w ArrayList< Person >(); 62 while 63 ( resultSet.next() ) { 64 results.add( 65 " a d d r e s s I D " ), 67 resultSet.getString( 68 resultSet.getString( " l a s t N a m e " ), 69 resultSet.getString( "email" ), 70 resultSet.getString( "phoneNumber" ) ) ); } 71 72 } { sqlException.print } // end catch { try 79 80 { resultSet.close(); 81 82 StackTrace(); finally 77 78 // end while // end try 75 76 "firstName" ), c a t c h ( SQLException sqlException ) 73 74 Executes the query in PreparedStatement selectAllPeople. PersonQueries .java (3 of 7 ) Process the ResultSet. n e w Person( resultSet.getInt( 66 Outline 118 } // end try © 1992-2007 Pearson Education, Inc. All rights reserved. c a t c h ( SQLException sqlException ) 83 { 84 Outline sqlException.printStackTrace(); 85 close(); 86 } 87 } 88 // end catch // end finally PersonQueries .java 89 return 90 91 119 } results; (4 of 7 ) // end method getAllPeople 92 // select person by last name 93 94 95 96 public List< Person > getPeopleByLastName( String name ) { 97 List< Person > results = 98 ResultSet resultSet = null ; null ; 99 try 100 101 102 { selectPeopleByLastName.setString( 1, name ); 103 104 // executeQuery returns ResultSet containing matching 105 resultSet = selectPeopleByLastName.executeQuery(); 106 107 results = n e w ArrayList< Person >(); Specify the parameter to PreparedStatement selectPeopleByLastName. entries Executes the query in PreparedStatement selectPeopleByLastName. // specify last name 108 © 1992-2007 Pearson Education, Inc. All rights reserved. while 109 ( resultSet.next() ) Process the ResultSet. { 110 results.add( 111 n e w Person( resultSet.getInt( 112 " a d d r e s s I D " ), 113 resultSet.getString( "firs t N a m e " ), 114 resultSet.getString( " l a s t N a m e " ), 115 resultSet.getString( "email" 116 resultSet.getString( "phoneNumber") ) ); } 117 } 118 Outline 120 // end while ), PersonQueries .java (5 of 7 ) // end try c a t c h ( SQLException sqlException ) 119 { 120 sqlException.printStackTrace(); 121 } 122 // end catch finally 123 { 124 try 125 { 126 resultSet.close(); 127 } 128 // end try c a t c h ( SQLException sqlException ) 129 { 130 sqlException.printStackTrace(); 131 close(); 132 } 133 } 134 // end catch // end finally 135 return 136 137 } results; // end method getPeopleByName 138 © 1992-2007 Pearson Education, Inc. All rights reserved. 139 // add an entry 140 public int String fname, String lname, String email, String num ) 141 142 addPerson( { int 143 result = 0; 144 // set parameters, then execute insertNewPerson 145 try 146 147 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(); } 157 Specify the parameters to PreparedStatement insertNewPerson. Executes the insert operation in PreparedStatement insertNewPerson. { sqlException.printStackTrace(); 158 close(); 159 160 // end try c a t c h ( SQLException sqlException ) 156 PersonQueries .java (6 of 7 ) { 148 155 Outline 121 } // end catch © 1992-2007 Pearson Education, Inc. All rights reserved. 161 r e t u r n result; 162 163 } // end method addPerson Outline 122 164 165 // close the database connection 166 public void 167 { try 168 PersonQueries .java (7 of 7 ) { 169 connection.close(); 170 } 171 // end try c a t c h ( SQLException sqlException ) 172 { 173 sqlException.printStackTrace(); 174 } 175 176 close() } // end catch // end method close 177 } // end interface PersonQueries © 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 L a y o u t ; 8 import java.awt.GridLayout; 9 i m p o r t java.util.List; Outline 123 AddressBook Display.java (1 of 14 ) 10 i m p o r t javax.swing.JButton; 11 i m p o r t javax.swing.Box; 12 i m p o r t javax.swing.JFrame; 13 i m p o r t javax.swing.JLabel; 14 i m p o r t javax.swing.JPanel; 15 i m p o r t javax.swing.JTextF ield; 16 i m p o r t javax.swing.WindowConstants; 17 i m p o r t javax.swing.BoxLayout; 18 i m p o r t javax.swing.BorderFactory; 19 i m p o r t javax.swing.JOptionPane; 20 21 public class AddressBookDisplay e x t e n d s JFrame 22 { 23 private Person currentEnt r y ; 24 private PersonQueries 25 p r i v a t e List< Person > results; 26 private int numberOfEntries = 27 private int currentEntryIndex; personQueries; 0; 28 29 private JButton browseButton; 30 private JLabel emailLabel; © 1992-2007 Pearson Education, Inc. All rights reserved. 31 private JTextField emailTextField; 32 private JLabel firstNameLabel; 33 private JTextField firstNameTextField; 34 private JLabel idLabel; 35 private JTextField idTextField; 36 private JTextField indexTextField; 37 p r i v a t e JLabel lastNameLabel; 38 private JTextField lastNameTextField; 39 private JTextField maxTextField; 40 private JButton nextButton; 41 private JLabel ofLabel; 42 private JLabel phoneLabel; 43 private JTextField phoneTextField 44 private JButton previousButton; 45 private JButton queryButton; 46 private JLabel queryLabel; 47 private JPanel queryPanel; 48 private JPanel navigatePanel; 49 private JPanel displayPanel; 50 private JTextField query 51 private JButton insertButton; Outline 124 AddressBook Display.java (2 of 14 ) ; TextField; 52 53 54 55 56 // no - argument public constructor AddressBookDisplay() { s u p e r( "Address Book" ); 57 58 // establish database connection and set up PreparedState 59 personQueries = ments n e w PersonQueries(); 60 © 1992-2007 Pearson Education, Inc. All rights reserved. 61 // create GUI 62 navigatePanel = 63 previousButton = n e w JButton(); 64 indexTextField = n e w JTextField( 65 ofLabel = 66 maxTextField = 67 nextButton = 68 displayPanel = 69 idLabel = 70 idTextField = 71 firstNameLabel = 72 firstNameTextField = 73 lastNameLabel = 74 lastNameTextField = n e w JPanel(); Outline 125 2 ); n e w JLabel(); n e w JTextField( 2 ); AddressBook Display.java n e w JButton(); n e w JPanel(); n e w JLabel(); n e w JTextField( (3 of 14 ) 1 0 ); n e w JLabel(); n e w JTextField( 1 0 ); n e w JLabel(); n e w JTextField( 75 emailLabel = 76 emailTextField = 77 phoneLabel = 78 phoneTextField = 79 queryPanel = n e w JPan el(); 80 queryLabel = n e w JLabel(); 81 queryTextField = 82 queryButton = 83 browseButton = n e w JButton(); 84 insertButton = n e w JButton(); 1 0 ); n e w JLabel(); n e w JTextField( 1 0 ); n e w JLabel(); n e w JTextField( n e w JTextField( 1 0 ); 1 0 ); n e w JButton(); 85 86 setLayout( 87 setSize( 88 n e w FlowLayout( FlowLayout.CENTER, 1 0, 1 0 ) ); 400, 300 ); setResizable( f a l s e ); 89 © 1992-2007 Pearson Education, Inc. All rights reserved. navigatePanel.setLayout( 90 n e w BoxLayout( navigatePanel, 91 B o x L a y o u t . X _ A X I S) ); 92 93 previousButton.setText( 94 previousButton.setEnabled( false ); ); previousButton.addActionListener( 95 AddressBook Display.java n e w ActionListener() 96 { 97 public void 98 actionPerformed( ActionEvent evt ) { 99 (4 of 14 ) previousButtonActionPerformed( evt ); 100 } 101 } 102 103 "Previous" Outline 126 ); // end method actionPerformed // end anonymous inner class // end call to addActionListener 104 navigatePanel.add( previousButton ); 105 navigatePanel.add( Box.createHorizontalStrut( 106 1 0 ) ); 107 indexTextField.setHorizontalAlignment( 108 JTextField.CENTER ); 109 indexTextField.addActionListener( 110 n e w ActionListener() 111 { 112 public void 113 { 114 indexTextFieldActionPerformed( evt ); 115 } 116 } 117 118 actionPerformed( ActionEvent evt ) ); // end method actionPerformed // end anonymous inner class // end call to addActionListener 119 © 1992-2007 Pearson Education, Inc. All rights reserved. navigatePanel.add( indexTextField ); 120 navigatePanel.add( Box.createHorizontalStrut( 121 1 0 ) ); Outline 122 ofLabel.setText( 123 "of" ); navigatePanel.add( ofLabel ); 124 navigatePanel.add( Box.createHorizontalStrut( 125 1 0 ) ); AddressBook Display.java 126 maxTextField.setHorizontalAlignment( 127 JTextField.CENTER ); 128 maxTextField.setEditable( 129 130 127 nav igatePanel.add( false maxTextField (5 of 14 ) ); ); navigatePanel.add( Box.createHorizontalStrut( 131 1 0 ) ); 132 133 nextButton.setText( 134 nextButton.setEnabled( f a l s e ); nextButton.addActionListener( 135 n e w ActionListener() 136 { 137 public void 138 actionPerformed( ActionEvent evt ) { 139 nextButtonActionPerformed( evt ); 140 } 141 } 142 143 "Next" ); ); // end method actionPerformed // end anonymous inner class // end call to addActionListener 144 145 146 navigatePanel.add( nextButton ); add( navigatePanel ); 147 148 displayPanel.setLayout( n e w GridLayout( 5, 2, 4, 4 ) ); © 1992-2007 Pearson Education, Inc. All rights reserved. 149 150 151 idLabel.setText( "Address ID:" ); Outline displayPanel.add( idLabel ); 128 152 153 idTextField.setEditable( f a l s e ); 154 displayPanel.add( idTextField ); 155 156 firstNameLabel.setText( "First Name:" 157 displayPanel.add( firstNameLabel ); 158 displayPanel.add( firstNameTextField ); ); AddressBook Display.java (6 of 14 ) 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 174 queryPanel.setLayout( n e w BoxLayout( queryPanel, B o x L a y o u t . X _ A X I S) ); 175 © 1992-2007 Pearson Education, Inc. All rights reserved. queryPanel.setBorder( BorderFactory.createTitledBorder( 176 "Find an entry by last name" 177 queryLabel.setText( 178 ) ); queryPanel.add( Box.createHorizontalStrut( 179 Outline "Last Name:" ); 5 ) ); queryPanel.add( queryLabel ); 180 queryPanel.add( Box.createHorizontalStrut( 181 10 ) ); queryPanel.add( queryTextField ); 182 queryPanel.add( Box.createHorizontalStrut( 183 1 0 ) ); 184 queryButton.setText( 185 "Find" AddressBook Display.java (7 of 14 ) ); queryButton.addActionListener( 186 n e w ActionListener() 187 { 188 public void 189 actionPerformed( ActionEvent evt ) { 190 queryButtonActionPerformed( evt ); 191 } 192 } 193 194 129 ); // end method actionPerformed // end anonymous inner class // end call to addActionListener 195 196 197 198 queryPanel.add( queryButton ); queryPanel.add( Box.createHorizontalStrut( 5 ) ); add( queryPanel ); 199 © 1992-2007 Pearson Education, Inc. All rights reserved. browseButton.setText( 200 ); browseButton.addActionListener( 201 Outline n e w ActionListener() 202 130 { 203 public void 204 actionPerformed( ActionEvent evt ) { 205 AddressBook Display.java browseButtonActionPerformed( evt ); 206 } 207 } 208 209 "Browse All Entries" ); // end method actionPerformed // end anonymous inner class (8 of 14 ) // end call to addActionListener 210 add( browseButton ); 211 212 insertButton.setText( 213 ); insertButton.addActionListener( 214 n e w ActionListener() 215 { 216 public void 217 actionPerformed( ActionEvent evt ) { 218 insertButtonActionPerformed( evt ); 219 } 220 } 221 222 "Insert New Entry" ); // end method actionPerformed // end anonymous inner class // end call to addActionListener 223 © 1992-2007 Pearson Education, Inc. All rights reserved. add( insertButton ); 224 Outline 225 addWindowListener( 226 131 n e w WindowAdapter() 227 { 228 public void 229 windowClosing( WindowEvent evt ) { 230 personQueries.close(); 231 System.exit( 232 } 233 } 234 ); 235 // close database connection 0 ); AddressBook Display.java (9 of 14 ) // end method windowClosing // end anonymous inner class // end call to addWindowListener 236 setVisible( 237 238 } t r u e ); // end no- argument constructor 239 240 // handles call when previousButton is clicked 241 private 242 void previousButtonActionPerformed( ActionEvent evt ) { currentEntryIndex 243 -- ; 244 if 245 ( currentEntryIndex < 0 ) currentEntryIndex = numberOfEntries 246 - 1; 247 248 indexTextField.setText( 249 indexTextFieldActionPerformed( evt ); 250 } "" + ( currentEntryIndex + 1 ) ); // end method previousButtonActionPerformed 251 © 1992-2007 Pearson Education, Inc. All rights reserved. 252 // handles call when nextButton is clicked 253 private 254 void nextButtonActionPerformed( ActionEvent evt ) Outline { 132 currentEntryIndex++; 255 256 if 257 ( currentEntryIndex >= numberOfEntries ) currentEn 258 tryIndex = AddressBook Display.java 0; 259 indexTextField.setText( 260 1 ) ); (10 of 14 ) indexTextFieldActionPerformed( evt ); 261 262 "" + ( currentEntryIndex + } // end method nextButtonActionPerformed 263 264 // handles call when queryButton is clicke 265 private 266 queryButtonActionPerformed( ActionEvent evt ) { results = 267 personQueries.getPeopleByLastName( 268 269 void d queryTextField.getText() numberO fEntries = results.size(); 270 if 271 272 273 274 275 ( numberOfEntries != 0 ) { currentEntryIndex = 0; currentEntry = results.get( currentEntryIndex ); idTextField.setText( "" + currentEntry.getAdd ressID() 276 firstNameTextField.setText( currentEntry.getFirstName() ); 277 lastNameTextField.setText( currentEntry.getLastName() ); 278 Executes the query in PreparedStatement ); selectPeopleByLastName from class PersonQueries. ); emailTextField.setText( currentEntry.getEmail() ); 279 phoneTextField.se tText( 280 maxTextField.setText( currentEntry.getPhoneNumber() ); "" + numberOfEntries ); © 1992-2007 Pearson Education, Inc. All rights reserved. 281 indexTextField.setText( 282 nextButton.setEnabled( 283 previousButton.setEnabled( } 284 1 ) ); t r u e ); Outline t r u e ); // end if browseButtonActionPerformed( evt ); 286 } AddressBook Display.java // end method queryButtonActionPerformed 288 289 // handles call when a new value is entered in indextTextField 290 private 291 133 else 285 287 "" + ( currentEntryIndex + void indexTextFiel dActionPerformed( ActionEvent evt ) (11 of 14 ) { currentEntryIndex = 292 ( Integer.parseInt( indexTextField.getText() ) 293 - 1 ); 294 if 295 ( numberOfEntries != 0 && currentEntryIndex < numberOfEntries ) { 296 currentEntry = results.get( currentEntryIndex ); 297 idTextField.setText("" + currentEntry.getAddressID() ); 298 299 firstNameTextField.setText( currentEntry.getFirstName() ); 300 lastNameTextField.setText( currentEntry.getLastName() ); 301 emailTextField.setText( currentEntry.getEmail() ); 302 phoneTextField.setText( currentEntry.getPhoneNumber() ); 303 maxTextField.setText( 304 indexTextField.setText( } 305 306 } "" + numberOfEntries ); "" + ( currentEntryIndex + 1 ) ); // end if // end method indexTextFieldActionPerformed 307 © 1992-2007 Pearson Education, Inc. All rights reserved. 308 // handles call when browseButton is clicked 309 private 310 void browseButtonActionPerformed( ActionEvent evt ) Outline { try 311 { 312 results 313 = personQueries.getAllPeople(); numberOfEntries = resul 314 ts.size(); 315 if 316 ( numberOfEntries != 0 ) { 317 currentEntryIndex = 318 Executes the query in PreparedStatement AddressBook Display.java selectAllPeople from class PersonQueries. (12 of 14 ) 0; currentEntry = results.get( currentEntryIndex ); 319 idTextField.setText( 320 "" + currentEntry.getAddr essID() ); 321 firstNameTextField.setText( currentEntry.getFirstName() ); 322 lastNameTextField.setText( currentEntry.getLastName() ); emailTextField.setText( currentEntry.getEmail() ); 323 phoneT 324 extField.setText( 325 maxTextField.setText( 326 indexTextField.setText( 327 nextButton.setEnabled( currentEntry.getPhoneNumber() } 329 } 330 ); "" + numberOfEntries ); "" + ( currentEntryIndex + 1 ) ); t r u e ); previousButton.setEnabled( 328 t r u e ); // end if // end try c a t c h ( Exception e ) 331 { 332 e.printStackTrace(); 333 } 334 335 134 } // end catch // end method browseButtonActionPerformed 336 © 1992-2007 Pearson Education, Inc. All rights reserved. 337 // handles call when insertButton is clicked 338 private 339 void insertButtonActionPerformed( ActionEvent evt ) { int 340 result = personQueries.addPerson( firstNameTextField.getText(), 341 lastNameTextField.getText() , emailTextField.getText(), 342 phoneTextField.getText() ); 343 if 344 ( result == 1 ) JOptionPane.showMessageDialog( 345 t h i s , "Person added!" , " P e r s o n added", JOptionPane.PLAIN_MESSAGE); 346 Outline 135 Executes the insert operation in PreparedStatement AddressBook insertNewPerson from class Display.java PersonQueries. (13 of 14 ) else 347 JOptionPane.showMessageDialog( 348 t h i s , "Person not added!" , " E r r o r " , JOptionPane.PLAIN_MESSAGE); 349 350 browseButtonActionPerformed( evt ); 351 352 } // end method insertButtonActionPerformed 353 354 // main method 355 public static void 356 { n e w AddressBookDisplay(); 357 358 main( String args[] ) } // end method main 359 } // end class AddressBookDisplay © 1992-2007 Pearson Education, Inc. All rights reserved. Outline 136 AddressBook Display.java (14 of 14 ) © 1992-2007 Pearson Education, Inc. All rights reserved. 137 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 © 2005 Pearson Education, Inc. All rights reserved. 138 Portability Tip 25.6 Although the syntax for creating stored procedures differs across database management systems, the interface CallableStatement provides a uniform interface for specifying input and output parameters for stored procedures and for invoking stored procedures. © 1992-2007 Pearson Education, Inc. All rights reserved. 139 Portability Tip 25.7 According to the Java API documentation for interface CallableStatement, for maximum portability between database systems, programs should process the update counts or ResultSets returned from a CallableStatement before obtaining the values of any output parameters. © 1992-2007 Pearson Education, Inc. All rights reserved. 140 25.13 Transaction Processing • Many applications require guarantees that a series of database insertions, updates and deletions executes properly before the applications continue processing the next database operation • Enables a program that interacts with a database to treat a database operation (or set of operations) as a single operation – Known as an atomic operation or a transaction – At the end of a transaction, decide to commit or roll back © 2005 Pearson Education, Inc. All rights reserved. 141 25.13 Transaction Processing • Committing a transaction finalizes the database operation(s); all insertions, updates and deletions performed as part of the transaction cannot be reversed without performing a new database operation • Rolling back a transaction leaves the database in its state prior to the database operation © 2005 Pearson Education, Inc. All rights reserved. 142 25.13 Transaction Processing • Methods of interface Connection – setAutoCommit specifies whether each SQL statement commits after it completes (a true argument) or if several SQL statements should be grouped as a transaction (a false argument) • If the argument to setAutoCommit is false, the program must follow the last SQL statement in the transaction with a call to Connection method commit or rollback – getAutoCommit determines the autocommit state for the Connection. © 2005 Pearson Education, Inc. All rights reserved.