Presentation is loading. Please wait.

Presentation is loading. Please wait.

 1992-2007 Pearson Education, Inc. All rights reserved. 1 25 Accessing Databases with JDBC.

Similar presentations


Presentation on theme: " 1992-2007 Pearson Education, Inc. All rights reserved. 1 25 Accessing Databases with JDBC."— Presentation transcript:

1  1992-2007 Pearson Education, Inc. All rights reserved. 1 25 Accessing Databases with JDBC

2  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.

3  1992-2007 Pearson Education, Inc. All rights reserved. 3 25.1Introduction 25.2Relational Databases 25.3Relational Database Overview: The books Database 25.4SQL 25.4.1 Basic SELECT Query 25.4.2 WHERE Claus 25.4.3 ORDER BY Claus 25.4.4Merging Data from Multiple Tables: INNER JOIN 25.4.5 INSERT Statement 25.4.6 UPDATE Statement 25.4.7 DELETE Statement 25.5Instructions for installing MySQL and MySQL Connector/J

4  1992-2007 Pearson Education, Inc. All rights reserved. 4 25.6Instructions for Setting Up a MySQL User Account 25.7 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

5  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

6  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

7  2005 Pearson Education, Inc. All rights reserved. 7 25.2 Relational Databases Relational database – Table Rows, columns – Primary key Unique data SQL queries – Specify which data to select from a table

8  1992-2007 Pearson Education, Inc. All rights reserved. 8 Fig. 25.1 | Employee table sample data.

9  1992-2007 Pearson Education, Inc. All rights reserved. 9 Fig. 25.2 | Result of selecting distinct Department and Location data from table Employee.

10  2005 Pearson Education, Inc. All rights reserved. 10 25.3 Relational Database Overview: The books Database Sample books database – Four tables authors – authorID, firstName, lastName titles – isbn, title, editionNumber, copyright, publisherID, imageFile, price authorISBN – authorID, isbn

11  1992-2007 Pearson Education, Inc. All rights reserved. 11 Fig. 25.3 | authors table from the books database.

12  1992-2007 Pearson Education, Inc. All rights reserved. 12 Fig. 25.4 | Sample data from the authors table.

13  2005 Pearson Education, Inc. All rights reserved. 13 25.3 Relational Database Overview: The books 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 ’ s primary key value

14  1992-2007 Pearson Education, Inc. All rights reserved. 14 Fig. 25.5 | authorISBN table from the books database.

15  1992-2007 Pearson Education, Inc. All rights reserved. 15 Fig. 25.6 | Sample data from the authorISBN table of books.

16  1992-2007 Pearson Education, Inc. All rights reserved. 16 Fig. 25.7 | titles table from the books database.

17  1992-2007 Pearson Education, Inc. All rights reserved. 17 Fig. 25.8 | Sample data from the titles table of the books database.

18  2005 Pearson Education, Inc. All rights reserved. 18 25.3 Relational Database Overview: The books 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

19  1992-2007 Pearson Education, Inc. All rights reserved. 19 Fig. 25.9 | Table relationships in the books database.

20  2005 Pearson Education, Inc. All rights reserved. 20 25.4 SQL SQL keywords – SQL queries and statements

21  1992-2007 Pearson Education, Inc. All rights reserved. 21 Fig. 25.10 | SQL query keywords.

22  2005 Pearson Education, Inc. All rights reserved. 22 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

23  1992-2007 Pearson Education, Inc. All rights reserved. 23 Fig. 25.11 | Sample authorID and lastName data from the authors table.

24  2005 Pearson Education, Inc. All rights reserved. 24 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

25  1992-2007 Pearson Education, Inc. All rights reserved. 25 Fig. 25.12 | Sampling of titles with copyrights after 2005 from table titles.

26  2005 Pearson Education, Inc. All rights reserved. 26 25.4.2 WHERE Clause (Cont.) WHERE clause condition operators –, =, =, <> – LIKE wildcard characters % and _ SELECT authorID, firstName, lastName FROM authors WHERE lastName LIKE ‘ D% ’

27  1992-2007 Pearson Education, Inc. All rights reserved. 27 Fig. 25.13 | Authors whose last name starts with D from the authors table.

28  2005 Pearson Education, Inc. All rights reserved. 28 25.4.2 WHERE Clause (Cont.) SELECT authorID, firstName, lastName FROM authors WHERE lastName LIKE ‘ _i% ’

29  1992-2007 Pearson Education, Inc. All rights reserved. 29 Fig. 25.14 | The only author from the authors table whose last name contains o as the second letter.

30  2005 Pearson Education, Inc. All rights reserved. 30 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

31  1992-2007 Pearson Education, Inc. All rights reserved. 31 Fig. 25.15 | Sample data from table authors in ascending order by lastName.

32  1992-2007 Pearson Education, Inc. All rights reserved. 32 Fig. 25.16 | Sample data from table authors in descending order by lastName.

33  2005 Pearson Education, Inc. All rights reserved. 33 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

34  1992-2007 Pearson Education, Inc. All rights reserved. 34 Fig. 25.17 | Sample data from authors in ascending order by lastName and firstName.

35  2005 Pearson Education, Inc. All rights reserved. 35 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

36  1992-2007 Pearson Education, Inc. All rights reserved. 36 Fig. 25.18 | Sampling of books from table titles whose titles end with How to Program in ascending order by title.

37  2005 Pearson Education, Inc. All rights reserved. 37 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

38  1992-2007 Pearson Education, Inc. All rights reserved. 38 Fig. 25.19 | Sampling of authors and ISBNs for the books they have written in ascending order by lastName and firstName.

39  2005 Pearson Education, Inc. All rights reserved. 39 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 ’ )

40  1992-2007 Pearson Education, Inc. All rights reserved. 40 Fig. 25.20 | Sample data from table Authors after an INSERT operation.

41  2005 Pearson Education, Inc. All rights reserved. 41 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 ’

42  1992-2007 Pearson Education, Inc. All rights reserved. 42 Fig. 25.21 | Sample data from table authors after an UPDATE operation.

43  2005 Pearson Education, Inc. All rights reserved. 43 25.4.7 DELETE Statement Remove data from a table – DELETE FROM tableName WHERE criteria DELETE FROM authors WHERE lastName = ‘ Jones ’ AND firstName = ‘ Sue ’

44  1992-2007 Pearson Education, Inc. All rights reserved. 44 Fig. 25.22 | Sample data from table authors after a DELETE operation.

45  2005 Pearson Education, Inc. All rights reserved. 45 25.5 Instructions to Install MySQL and MySQL 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 – Double click mysql-essential-5.0.27-win32.msi to start the installer. – Choose typical for the Setup Type and click Next >. Then click install.

46  2005 Pearson Education, Inc. All rights reserved. 46 25.5 Instructions to Install MySQL and MySQL Connector/J 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.

47  2005 Pearson Education, Inc. All rights reserved. 47 25.5 Instructions to Install MySQL and MySQL 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 of mysql-connector-java-5.0.4 – Docs also online at dev.mysql.com/doc/connector/j/en/ connector-j.html

48  2005 Pearson Education, Inc. All rights reserved. 48 25.6 Instructions on Setting MySQL User Account 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;

49  2005 Pearson Education, Inc. All rights reserved. 49 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;

50  2005 Pearson Education, Inc. All rights reserved. 50 25.8 Manipulating Databases with JDBC Connect to a database Query the database Display the results of the query in JTable

51  2005 Pearson Education, Inc. All rights reserved. 51 25.8.1 Connecting to and Querying a Database 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

52  1992-2007 Pearson Education, Inc. All rights reserved. 52 Outline DisplayAuthors. java (1 of 3 ) Imports for the JDBC classes and interfaces from package java.sql Declare a String constant that specifies the JDBC driver’s class name Loads the class definition for the database driver. Declare a String constant that specifies the database URL

53  1992-2007 Pearson Education, Inc. All rights reserved. 53 Outline DisplayAuthors. java (2 of 3 ) Invokes Connection method createStatement to obtain an object that implements interface Statement. Use the Statement object’s executeQuery method to execute a query that selects all the author information from table authors. Obtains the metadata for the ResultSet. Uses ResultSetMetaData method getColumnCount to retrieve the number of columns in the ResultSet. Obtain column name using method getColumnName Position the ResultSet cursor to the first row in the ResultSet with method next Extract the contents of one column in the current row Initialize a Connection reference called connection.

54  1992-2007 Pearson Education, Inc. All rights reserved. 54 Outline DisplayAuthors. java (3 of 3 ) Catch SQLException, which is thrown if the query execution or ResultSet process fails ClassNotFoundException is thrown if the class loader cannot locate the driver class Close the Statement and the database Connection.

55  1992-2007 Pearson Education, Inc. All rights reserved. 55 Fig. 25.24 | Popular JDBC database URL formats.

56  2005 Pearson Education, Inc. All rights reserved. 56 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

57  1992-2007 Pearson Education, Inc. All rights reserved. 57 Outline ResultSetTable Model.java (1 of 7 ) Class ResultSetTableModel extends class AbstractTableModel, which implements interface TableModel. Instance variable keeps track of database connection status

58  1992-2007 Pearson Education, Inc. All rights reserved. 58 Outline ResultSetTable Model.java (2 of 7 ) Establishes a connection to the database. Invokes Connection method createStatement to create a Statement object. Constructor accepts five String arguments—the driver class name, the database URL, the username, the password and the default query to perform Indicate that connect to database is successful Invokes ResultSetTableModel method setQuery to perform the default query.

59  1992-2007 Pearson Education, Inc. All rights reserved. 59 Outline ResultSetTable Model.java (3 of 7 ) Override method getColumnClass to obtain a Class object that represents the superclass of all objects in a particular column Verify database connection status Loads the class definition for the class and returns the corresponding Class object. Returns the default type. Obtains the fully qualified class name for the specified column. Override method getColumnCount to obtain the number of columns in the model’s underlying ResultSet

60  1992-2007 Pearson Education, Inc. All rights reserved. 60 Outline ResultSetTable Model.java (4 of 7 ) Obtains the number of columns in the ResultSet. Override method getColumnName to obtain the name of the column in the model’s underlying ResultSet Obtains the column name from the ResultSet.

61  1992-2007 Pearson Education, Inc. All rights reserved. 61 Outline ResultSetTable Model.java (5 of 7 ) Override method getColumnCount to obtain the number of rows in the model’s underlying ResultSet Uses ResultSet method absolute to position the ResultSet cursor at a specific row. Override method getValueAt to obtain the Object in a particular row and column of the model’s underlying ResultSet Uses ResultSet method getObject to obtain the Object in a specific column of the current row.

62  1992-2007 Pearson Education, Inc. All rights reserved. 62 Outline ResultSetTable Model.java (6 of 7 ) Executes the query to obtain a new ResultSet. Uses ResultSet method last to position the ResultSet cursor at the last row in the ResultSet. Uses ResultSet method getRow to obtain the row number for the current row in the ResultSet. Invokes method fireTableAStructureChanged to notify any JTable using this ResultSetTableModel object as its model that the structure of the model has changed.

63  1992-2007 Pearson Education, Inc. All rights reserved. 63 Outline ResultSetTable Model.java (7 of 7 ) Method disconnectFromDatabase implement an appropriate termination method for class ResultSetTableModel Verify whether the connection is already terminated Close the Statement and Connection if a ResultSetTableModel object is garbage collected. Set connectedToDatabase to false to ensure that clients do not use an instance of ResultSetTableModel after that instance has already been terminated

64  1992-2007 Pearson Education, Inc. All rights reserved. 64 Fig. 25.26 | ResultSet constants for specifying ResultSet type.

65  1992-2007 Pearson Education, Inc. All rights reserved. 65 Fig. 25.27 | ResultSet constants for specifying result properties.

66  2005 Pearson Education, Inc. All rights reserved. 66 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

67  2005 Pearson Education, Inc. All rights reserved. 67 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

68  1992-2007 Pearson Education, Inc. All rights reserved. 68 Portability Tip 25.5 A RowSet can provide scrolling capability for drivers that do not support scrollable ResultSet s.

69  1992-2007 Pearson Education, Inc. All rights reserved. 69 Outline JdbcRowSetTest. java (1 of 3 )

70  1992-2007 Pearson Education, Inc. All rights reserved. 70 Outline JdbcRowSetTest. java (2 of 3 ) Use Sun’s reference implementation of JdbcRowSet interface ( JdbcRowSetImpl ) to create a JdbcRowSet object Invoke JdbcRowSet method setUrl to specify the database URL Invoke JdbcRowSet method setUsername to specify the username Invoke JdbcRowSet method setUsername to specify the password Invoke JdbcRowSet method setCommand to specify the query Invoke JdbcRowSet method execute to execute the query

71  1992-2007 Pearson Education, Inc. All rights reserved. 71 Outline JdbcRowSetTest. java (3 of 3 )


Download ppt " 1992-2007 Pearson Education, Inc. All rights reserved. 1 25 Accessing Databases with JDBC."

Similar presentations


Ads by Google