2005 Pearson Education, Inc. All rights reserved. 1 25 Accessing Databases with JDBC.

109
1 2005 Pearson Education, Inc. All rights rese 2 5 Accessing Databases with JDBC

Transcript of 2005 Pearson Education, Inc. All rights reserved. 1 25 Accessing Databases with JDBC.

Page 1: 2005 Pearson Education, Inc. All rights reserved. 1 25 Accessing Databases with JDBC.

1

2005 Pearson Education, Inc. All rights reserved.

2525

Accessing Databases with

JDBC

Page 2: 2005 Pearson Education, Inc. All rights reserved. 1 25 Accessing Databases with JDBC.

2

2005 Pearson Education, Inc. All rights reserved.

It is a capital mistake to theorize before one has data.

— Arthur Conan Doyle

Now go, write it before them in a table, and note it in a book, that it may be for the time to come for ever and ever.

— The Holy Bible, Isaiah 30:8

Get your facts first, and then you can distort them as much as you please.

— Mark Twain

I like two kinds of men: domestic and foreign.— Mae West

Page 3: 2005 Pearson Education, Inc. All rights reserved. 1 25 Accessing Databases with JDBC.

3

2005 Pearson Education, Inc. All rights reserved.

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.

Page 4: 2005 Pearson Education, Inc. All rights reserved. 1 25 Accessing Databases with JDBC.

4

2005 Pearson Education, Inc. All rights reserved.

25.1   Introduction 25.2   Relational Databases25.3   Relational Database Overview: The books Database 25.4   SQL

25.4.1  Basic SELECT Query 25.4.2  WHERE Clause 25.4.3  ORDER BY Clause 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

25.5   Instructions to install MySQL and MySQL Connector/J 25.6   Instructions on Setting MySQL User Account 25.7   Creating Database books 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   Stored Procedures 25.10  RowSet Interface 25.11  Wrap-Up

Page 5: 2005 Pearson Education, Inc. All rights reserved. 1 25 Accessing Databases with JDBC.

5

2005 Pearson Education, Inc. All rights reserved.

25.1 Introduction

• Database– Collection of data

• DBMS– Database management system

– Storing and organizing data

• SQL– Relational database

– Structured Query Language

Page 6: 2005 Pearson Education, Inc. All rights reserved. 1 25 Accessing Databases with JDBC.

6

2005 Pearson Education, Inc. All rights reserved.

25.1 Introduction (Cont.)

• RDBMS– Relational database management system– MySQL

• Open source• Available for both Windows and Linux• dev.mysql.com/downloads/mysql/4.0.hml

• JDBC– Java Database Connectivity– JDBC driver

• Enable Java applications to connect to database• Enable programmers to manipulate databases using JDBC

Page 7: 2005 Pearson Education, Inc. All rights reserved. 1 25 Accessing Databases with JDBC.

7

2005 Pearson Education, Inc. All rights reserved.

Software Engineering Observation 25.1

The separation of the JDBC API from particular database drivers enables developers to change the underlying database without modifying the Java code that accesses the database.

Page 8: 2005 Pearson Education, Inc. All rights reserved. 1 25 Accessing Databases with JDBC.

8

2005 Pearson Education, Inc. All rights reserved.

25.2 Relational Databases

• Relational database– Table

• Rows, columns

– Primary key• Unique data

• SQL queries– Specify which data to select from a table

Page 9: 2005 Pearson Education, Inc. All rights reserved. 1 25 Accessing Databases with JDBC.

9

2005 Pearson Education, Inc. All rights reserved.

Fig. 25.1 | Employee table sample data.

Page 10: 2005 Pearson Education, Inc. All rights reserved. 1 25 Accessing Databases with JDBC.

10

2005 Pearson Education, Inc. All rights reserved.

Fig. 25.2 | Result of selecting distinct Department and Location data from table Employee.

Page 11: 2005 Pearson Education, Inc. All rights reserved. 1 25 Accessing Databases with JDBC.

11

2005 Pearson Education, Inc. All rights reserved.

25.3 Relational Database Overview: The books Database

• Sample books database– Four tables

• authors

– authorID, firstName, lastName

• publishers

– publisherID, publisherName

• titles

– isbn, title, editionNumber, copyright, publisherID, imageFile, price

• authorISBN

– authorID, isbn

Page 12: 2005 Pearson Education, Inc. All rights reserved. 1 25 Accessing Databases with JDBC.

12

2005 Pearson Education, Inc. All rights reserved.

Fig. 25.3 | authors table from books.

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).

Page 13: 2005 Pearson Education, Inc. All rights reserved. 1 25 Accessing Databases with JDBC.

13

2005 Pearson Education, Inc. All rights reserved.

Fig. 25.4 | Sample data from the authors table.

authorID firstName lastName

1 Harvey Deitel

2 Paul Deitel

3 Tem Nieto

4 Sean Santry

Page 14: 2005 Pearson Education, Inc. All rights reserved. 1 25 Accessing Databases with JDBC.

14

2005 Pearson Education, Inc. All rights reserved.

Fig. 25.5 | publishers table from books.

Column Description

publisherID The publisher’s ID number in the database. This autoincremented integer is the table’s primary key.

publisherName The name of the publisher (a string).

Page 15: 2005 Pearson Education, Inc. All rights reserved. 1 25 Accessing Databases with JDBC.

15

2005 Pearson Education, Inc. All rights reserved.

Fig. 25.6 | Data from the publishers table.

publisherID publisherName

1 Prentice Hall

2 Prentice Hall PTG

Page 16: 2005 Pearson Education, Inc. All rights reserved. 1 25 Accessing Databases with JDBC.

16

2005 Pearson Education, Inc. All rights reserved.

Fig. 25.7 | titles table from books.

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 worldwide use to give every book a unique identification number.

title Title of the book (a string).

editionNumber Edition number of the book (an integer).

copyright Copyright year of the book (a string).

publisherID Publisher’s ID number (an integer). A foreign key that relates this table to the publishers table.

imageFile Name of the file containing the book’s cover image (a string).

price Suggested retail price of the book (a real number). [Note: The prices shown in Fig. 25.8 are for example purposes only.]

Page 17: 2005 Pearson Education, Inc. All rights reserved. 1 25 Accessing Databases with JDBC.

17

2005 Pearson Education, Inc. All rights reserved.

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

• Entity-relationship (ER) diagram– Tables in the database

– Relationships among tables

Page 18: 2005 Pearson Education, Inc. All rights reserved. 1 25 Accessing Databases with JDBC.

18

2005 Pearson Education, Inc. All rights reserved.

25.3 Relational Database Overview: The books Database (Cont.)

• 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

Page 19: 2005 Pearson Education, Inc. All rights reserved. 1 25 Accessing Databases with JDBC.

19

2005 Pearson Education, Inc. All rights reserved.

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.

Page 20: 2005 Pearson Education, Inc. All rights reserved. 1 25 Accessing Databases with JDBC.

20

2005 Pearson Education, Inc. All rights reserved.

Common Programming Error 25.2

Providing the same value for the primary key in multiple rows causes the DBMS to report an error.

Page 21: 2005 Pearson Education, Inc. All rights reserved. 1 25 Accessing Databases with JDBC.

21

2005 Pearson Education, Inc. All rights reserved.

Fig. 25.8 | Sample data from the titles table of books.

isbn

title

editionNumber

copy- right

publisherID

Image File price

0131426443 C How to Program

4 2004 1 chtp4.jpg 85.00

0130384747 C++ How to Program

4 2003 1 cpphtp4.jpg

85.00

0130461342 Java Web Services for Experienced Programmers

1 2003 1 jwsfep1.jpg

54.99

0131483986 Java How to Program

6 2005 1 jhtp6.jpg 85.00

013100252X The Complete C++ Training Course

4 2003 2 cppctc4.jpg

109.99

0130895601 Advanced Java 2 Platform How to Program

1 2002 1 advjhtp1.jpg

69.95

Page 22: 2005 Pearson Education, Inc. All rights reserved. 1 25 Accessing Databases with JDBC.

22

2005 Pearson Education, Inc. All rights reserved.

Fig. 25.9 | authorISBN table from books.

Column Description

authorID The author’s ID number, a foreign key to the authors table.

isbn The ISBN for a book, a foreign key to the titles table.

Page 23: 2005 Pearson Education, Inc. All rights reserved. 1 25 Accessing Databases with JDBC.

23

2005 Pearson Education, Inc. All rights reserved.

Fig. 25.10 | Sample data from the authorISBN table of books.

authorID isbn authorID isbn

1 0130895725 2 0139163050

2 0130895725 3 0130829293

2 0132261197 3 0130284173

2 0130895717 3 0130284181

2 0135289106 4 0130895601

Page 24: 2005 Pearson Education, Inc. All rights reserved. 1 25 Accessing Databases with JDBC.

24

2005 Pearson Education, Inc. All rights reserved.

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.

Page 25: 2005 Pearson Education, Inc. All rights reserved. 1 25 Accessing Databases with JDBC.

25

2005 Pearson Education, Inc. All rights reserved.

Fig. 25.11 | Table relationships in books.

Page 26: 2005 Pearson Education, Inc. All rights reserved. 1 25 Accessing Databases with JDBC.

26

2005 Pearson Education, Inc. All rights reserved.

25.4 SQL

• SQL keywords– SQL queries and statements

Page 27: 2005 Pearson Education, Inc. All rights reserved. 1 25 Accessing Databases with JDBC.

27

2005 Pearson Education, Inc. All rights reserved.

Fig. 25.12 | SQL query keywords.

SQL keyword Description

SELECT Retrieves data from one or more tables.

FROM Tables involved in the query. Required in every SELECT.

WHERE Criteria for selection that determine the rows to be retrieved, deleted or updated. Optional in a SQL query or a SQL statement.

GROUP BY Criteria for grouping rows. Optional in a SELECT query.

ORDER BY Criteria for ordering rows. Optional in a SELECT query.

INNER JOIN Merge rows from multiple tables.

INSERT Insert rows into a specified table.

UPDATE Update rows in a specified table.

DELETE Delete rows from a specified table.

Page 28: 2005 Pearson Education, Inc. All rights reserved. 1 25 Accessing Databases with JDBC.

28

2005 Pearson Education, Inc. All rights reserved.

25.4.1 Basic SELECT Query

• Simplest format of a SELECT query– SELECT * FROM tableName

• SELECT * FROM authors

• Select specific fields from a table– SELECT authorID, lastName FROM authors

Page 29: 2005 Pearson Education, Inc. All rights reserved. 1 25 Accessing Databases with JDBC.

29

2005 Pearson Education, Inc. All rights reserved.

Fig. 25.13 | Sample authorID and lastName data from the authors table.

authorID lastName

1 Deitel

2 Deitel

3 Nieto

4 Santry

Page 30: 2005 Pearson Education, Inc. All rights reserved. 1 25 Accessing Databases with JDBC.

30

2005 Pearson Education, Inc. All rights reserved.

Software Engineering Observation 25.2

For most queries, the asterisk (*) should not be used to specify column names. In general, programmers 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).

Page 31: 2005 Pearson Education, Inc. All rights reserved. 1 25 Accessing Databases with JDBC.

31

2005 Pearson Education, Inc. All rights reserved.

Common Programming Error 25.4

If a programmer assumes that the columns are always returned in the same order from a query that uses the asterisk (*), the program may process the result 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.

Page 32: 2005 Pearson Education, Inc. All rights reserved. 1 25 Accessing Databases with JDBC.

32

2005 Pearson Education, Inc. All rights reserved.

25.4.2 WHERE Clause

• specify the selection criteria– SELECT columnName1, columnName2, … FROM tableName WHERE criteria

• SELECT title, editionNumber, copyright

FROM titles

WHERE copyright > 2002

Page 33: 2005 Pearson Education, Inc. All rights reserved. 1 25 Accessing Databases with JDBC.

33

2005 Pearson Education, Inc. All rights reserved.

Fig. 25.14 | Sampling of titles with copyrights after 2002 from table titles.

title editionNumber copyright

The Complete C++ Training Course 4 2003

Java How to Program 5 2003

C How to Program 4 2004

Internet and World Wide Web How to Program

3 2004

Java How to Program 6 2005

C# How to Program 1 2003

Page 34: 2005 Pearson Education, Inc. All rights reserved. 1 25 Accessing Databases with JDBC.

34

2005 Pearson Education, Inc. All rights reserved.

25.4.2 WHERE Clause (Cont.)

•WHERE clause condition operators– <, >, <=, >=, =, <>

– LIKE• wildcard characters % and _

• SELECT authorID, firstName, lastName

FROM authors

WHERE lastName LIKE ‘D%’

Page 35: 2005 Pearson Education, Inc. All rights reserved. 1 25 Accessing Databases with JDBC.

35

2005 Pearson Education, Inc. All rights reserved.

Fig. 25.15 | Authors whose last name starts with D from the authors table.

authorID firstName lastName

1 Harvey Deitel

2 Paul Deitel

Page 36: 2005 Pearson Education, Inc. All rights reserved. 1 25 Accessing Databases with JDBC.

36

2005 Pearson Education, Inc. All rights reserved.

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?).

Page 37: 2005 Pearson Education, Inc. All rights reserved. 1 25 Accessing Databases with JDBC.

37

2005 Pearson Education, Inc. All rights reserved.

Portability Tip 25.2

Read your database system’s documentation carefully to determine whether your system supports the LIKE operator.

Page 38: 2005 Pearson Education, Inc. All rights reserved. 1 25 Accessing Databases with JDBC.

38

2005 Pearson Education, Inc. All rights reserved.

Portability Tip 25.3

Some databases use the * character in place of the % character in a pattern.

Page 39: 2005 Pearson Education, Inc. All rights reserved. 1 25 Accessing Databases with JDBC.

39

2005 Pearson Education, Inc. All rights reserved.

25.4.2 WHERE Clause (Cont.)

• SELECT authorID, firstName, lastName

FROM authors

WHERE lastName LIKE ‘_i%’

Page 40: 2005 Pearson Education, Inc. All rights reserved. 1 25 Accessing Databases with JDBC.

40

2005 Pearson Education, Inc. All rights reserved.

Fig. 25.16 | The only author from the authors table whose last name contains i as the second letter.

authorID firstName lastName

3 Tem Nieto

Page 41: 2005 Pearson Education, Inc. All rights reserved. 1 25 Accessing Databases with JDBC.

41

2005 Pearson Education, Inc. All rights reserved.

Portability Tip 25.4

Some database systems use the ? character in place of the _ character in a pattern.

Page 42: 2005 Pearson Education, Inc. All rights reserved. 1 25 Accessing Databases with JDBC.

42

2005 Pearson Education, Inc. All rights reserved.

25.4.3 ORDER BY Clause

• Optional ORDER BY clause– SELECT columnName1, columnName2, … FROM tableName ORDER BY column ASC• SELECT authorID, firstName, lastName

FROM authors

ORDER BY lastName ASC

– SELECT columnName1, columnName2, … FROM tableName ORDER BY column DESC• SELECT authorID, firstName, lastName

FROM authors

ORDER BY lastName DESC

Page 43: 2005 Pearson Education, Inc. All rights reserved. 1 25 Accessing Databases with JDBC.

43

2005 Pearson Education, Inc. All rights reserved.

Fig. 25.17 | Sample data from table authors in ascending order by lastName.

authorID firstName lastName

1 Harvey Deitel

2 Paul Deitel

3 Tem Nieto

4 Sean Santry

Page 44: 2005 Pearson Education, Inc. All rights reserved. 1 25 Accessing Databases with JDBC.

44

2005 Pearson Education, Inc. All rights reserved.

Fig. 25.18 | Sample data from table authors in descending order by lastName.

authorID firstName lastName

4 Sean Santry

3 Tem Nieto

1 Harvey Deitel

2 Paul Deitel

Page 45: 2005 Pearson Education, Inc. All rights reserved. 1 25 Accessing Databases with JDBC.

45

2005 Pearson Education, Inc. All rights reserved.

25.4.3 ORDER BY Clause (Cont.)

•ORDER BY multiple fields– ORDER BY column1 sortingOrder, column2 sortingOrder, …

• SELECT authorID, firstName, lastName

FROM authors

ORDER BY lastName, firstName

Page 46: 2005 Pearson Education, Inc. All rights reserved. 1 25 Accessing Databases with JDBC.

46

2005 Pearson Education, Inc. All rights reserved.

Fig. 25.19 | Sample data from authors in ascending order by lastName and firstName.

authorID firstName lastName

1 Harvey Deitel

2 Paul Deitel

3 Tem Nieto

4 Sean Santry

Page 47: 2005 Pearson Education, Inc. All rights reserved. 1 25 Accessing Databases with JDBC.

47

2005 Pearson Education, Inc. All rights reserved.

25.4.3 ORDER BY Clause (Cont.)

• Combine the WHERE and ORDER BY clauses• SELECT isbn, title, editionNumber, copyright, price

FROM titles WHERE title LIKE ‘%How to Program’

ORDER BY title ASC

Page 48: 2005 Pearson Education, Inc. All rights reserved. 1 25 Accessing Databases with JDBC.

48

2005 Pearson Education, Inc. All rights reserved.

Fig. 25.20 | Sampling of books from table titles whose titles end with How to Program in ascending order by title.

isbn

title

Edition -Number

copy-right

price

0130895601 Advanced Java 2 Platform How to Program

1 2002 69.95

0131426443 C How to Program 4 2004 85.00

0130384747 C++ How to Program 4 2003 85.00

013028419x e-Business and e-Commerce How to Program

1 2001 69.95

0131450913 Internet and World Wide Web How to Program

3 2004 85.00

0130284181 Perl How to Program 1 2001 69.95

0134569555 Visual Basic 6 How to Program 1 1999 69.95

0130284173 XML How to Program 1 2001 69.95

Page 49: 2005 Pearson Education, Inc. All rights reserved. 1 25 Accessing Databases with JDBC.

49

2005 Pearson Education, Inc. All rights reserved.

25.4.4 Merging Data from Multiple Tables: INNER JOIN

• Split related data into separate tables• Join the tables

– Merge data from multiple tables into a single view– INNER JOIN

• SELECT columnName1, columnName2, … FROM table1

INNER JOIN table2 ON table1.columnName = table2.column2Name

• SELECT firstName, lastName, isbn FROM authors, authorISBN INNER JOIN authorISBN

ON authors.authorID = authorISBN.authorID ORDER BY lastName, firstName

Page 50: 2005 Pearson Education, Inc. All rights reserved. 1 25 Accessing Databases with JDBC.

50

2005 Pearson Education, Inc. All rights reserved.

Software Engineering Observation 25.3

If a SQL statement includes columns from multiple tables that have the same name, the statement must precede those column names with their table names and a dot (e.g., authors.authorID).

Page 51: 2005 Pearson Education, Inc. All rights reserved. 1 25 Accessing Databases with JDBC.

51

2005 Pearson Education, Inc. All rights reserved.

Common Programming Error 25.5

In a query, failure to qualify names for columns that have the same name in two or more tables is an error.

Page 52: 2005 Pearson Education, Inc. All rights reserved. 1 25 Accessing Databases with JDBC.

52

2005 Pearson Education, Inc. All rights reserved.

Fig. 25.21 | Sampling of authors and ISBNs for the books they have written in ascending order by lastName and firstName.

firstName

lastName

isbn

first Name

lastName

isbn

Harvey Deitel 0130895601 Paul Deitel 0130895717

Harvey Deitel 0130284181 Paul Deitel 0132261197

Harvey Deitel 0134569555 Paul Deitel 0130895725

Harvey Deitel 0139163050 Paul Deitel 0130829293

Harvey Deitel 0135289106 Paul Deitel 0134569555

Harvey Deitel 0130895717 Paul Deitel 0130829277

Harvey Deitel 0130284173 Tem Nieto 0130161438

Harvey Deitel 0130829293 Tem Nieto 013028419x

Paul Deitel 0130852473 Sean Santry 0130895601

Page 53: 2005 Pearson Education, Inc. All rights reserved. 1 25 Accessing Databases with JDBC.

53

2005 Pearson Education, Inc. All rights reserved.

25.4.5 INSERT Statement

• Insert a row into a table– INSERT INTO tableName ( columnName1, … , columnNameN )

VALUES ( value1, … , valueN )

• INSERT INTO authors ( firstName, lastName )

VALUES ( ‘Sue’, ‘Smith’ )

Page 54: 2005 Pearson Education, Inc. All rights reserved. 1 25 Accessing Databases with JDBC.

54

2005 Pearson Education, Inc. All rights reserved.

Fig. 25.22 | Sample data from table Authors after an INSERT operation.

authorID firstName lastName

1 Harvey Deitel 2 Paul Deitel 3 Tem Nieto 4 Sean Santry 5 Sue Smith

Page 55: 2005 Pearson Education, Inc. All rights reserved. 1 25 Accessing Databases with JDBC.

55

2005 Pearson Education, Inc. All rights reserved.

Common Programming Error 25.6

It is an error to specify a value for an autoincrement column.

Page 56: 2005 Pearson Education, Inc. All rights reserved. 1 25 Accessing Databases with JDBC.

56

2005 Pearson Education, Inc. All rights reserved.

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.

Page 57: 2005 Pearson Education, Inc. All rights reserved. 1 25 Accessing Databases with JDBC.

57

2005 Pearson Education, Inc. All rights reserved.

25.4.6 UPDATE Statement

• Modify data in a table– UPDATE tableName

SET columnName1 = value1, … , columnNameN = valueN

WHERE criteria

• UPDATE authors

SET lastName = ‘Jones’

WHERE lastName = ‘Smith’ AND firstName = ‘Sue’

Page 58: 2005 Pearson Education, Inc. All rights reserved. 1 25 Accessing Databases with JDBC.

58

2005 Pearson Education, Inc. All rights reserved.

Fig. 25.23 | Sample data from table authors after an UPDATE operation.

authorID firstName lastName

1 Harvey Deitel 2 Paul Deitel 3 Tem Nieto 4 Sean Santry 5 Sue Jones

Page 59: 2005 Pearson Education, Inc. All rights reserved. 1 25 Accessing Databases with JDBC.

59

2005 Pearson Education, Inc. All rights reserved.

25.4.7 DELETE Statement

• Remove data from a table– DELETE FROM tableName WHERE criteria

• DELETE FROM authors

WHERE lastName = ‘Jones’ AND firstName = ‘Sue’

Page 60: 2005 Pearson Education, Inc. All rights reserved. 1 25 Accessing Databases with JDBC.

60

2005 Pearson Education, Inc. All rights reserved.

Fig. 25.24 | Sample data from table authors after a DELETE operation.

authorID firstName lastName

1 Harvey Deitel 2 Paul Deitel 3 Tem Nieto 4 Sean Santry

Page 61: 2005 Pearson Education, Inc. All rights reserved. 1 25 Accessing Databases with JDBC.

61

2005 Pearson Education, Inc. All rights reserved.

25.5 Instructions to Install MySQL and MySQL Connector/J

• Install MySQL– Insert CD and change directory to D:\software\MySQL\mysql-4.0.20c-win

– Double click SETUP.EXE

– Following the instruction

• Install MySQL Connector/J– Copy mysql-connector-java-3.0.14-production.zip

– Open mysql-connector-java-3.0.14-production.zip• Extract its content to the C:\ driv

Page 62: 2005 Pearson Education, Inc. All rights reserved. 1 25 Accessing Databases with JDBC.

62

2005 Pearson Education, Inc. All rights reserved.

25.6 Instructions on Setting MySQL User Account

• Set up a user account– Start database server by executing the script C:\mysql\bin\mysqld

– Start the MySQL monitor by executing the command C:\mysql\bin>mysql –h localhost –u root

– Create an account mysql> USE mysql;mysql> INSERT INTO user SET Host=‘localhost’,

User=‘jhtp6’, Password=PASSWORD(‘jhtp6’), Select_priv=‘Y’,

Insert_priv=‘Y’, Update_priv=‘Y’, Delete_priv=‘Y’, Create_priv=‘Y’, Drop_priv=‘Y’, References_priv=‘Y’, Execute_priv=‘Y’;

mysql> FLUSH PRIVILEGES;mysql> exit;

Page 63: 2005 Pearson Education, Inc. All rights reserved. 1 25 Accessing Databases with JDBC.

63

2005 Pearson Education, Inc. All rights reserved.

25.7 Creating Database books in MySQL

• Create books database– Open Command Prompt

– Change to the C:\mysql\bin directory

– Start database by executing the command C:\mysql\bin\mysqld

– Copy SQL script books.sql to C:\mysql\bin directory

– Open another Command Prompt

– Change to the C:\mysql\bin directory

– Create the books database by executing the command C:\mysql\bin>mysql –h localhost –u jhtp6 –p < books.sql

Page 64: 2005 Pearson Education, Inc. All rights reserved. 1 25 Accessing Databases with JDBC.

64

2005 Pearson Education, Inc. All rights reserved.

25.8 Manipulating Databases with JDBC

• Connect to a database

• Query the database

• Display the results of the query in JTable

Page 65: 2005 Pearson Education, Inc. All rights reserved. 1 25 Accessing Databases with JDBC.

65

2005 Pearson Education, Inc. All rights reserved.

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

Page 66: 2005 Pearson Education, Inc. All rights reserved. 1 25 Accessing Databases with JDBC.

66

2005 Pearson Education, Inc. All rights reserved.

Outline

DisplayAuthors .java

(1 of 3)

Lines 3-8

Line 13

Line 14

Line 25

Lines 28-29

1 // Fig. 25.25: 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.ResultSetMetaData;

8 import java.sql.SQLException;

9

10 public class DisplayAuthors

11 {

12 // JDBC driver name and database URL

13 static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";

14 static final String DATABASE_URL = "jdbc:mysql://localhost/books";

15

16 // launch the application

17 public static void main( String args[] )

18 {

19 Connection connection = null; // manages connection

20 Statement statement = null; // query statement

21

22 // connect to database books and query database

23 try

24 {

25 Class.forName( JDBC_DRIVER ); // load database driver class

26

27 // establish connection to database

28 connection =

29 DriverManager.getConnection( DATABASE_URL, "jhtp6", "jhtp6" );

30

Imports the JDBC classes and interfaces from package java.sql

Declare a String constant that specifies the JDBC driver’s class name

Declare a String constant that specifies the database URL

Loads the class definition for the database driver.

Declare and initialize a Connection reference called connection.

Page 67: 2005 Pearson Education, Inc. All rights reserved. 1 25 Accessing Databases with JDBC.

67

2005 Pearson Education, Inc. All rights reserved.

Outline

DisplayAuthors .java

(2 of 3)

Line 32

Lines 35-36

Line 39

Line 40

Line 44

Line 47

Line 50

Line 54

31 // create Statement for querying database

32 statement = connection.createStatement();

33

34 // query database

35 ResultSet resultSet = statement.executeQuery(

36 "SELECT authorID, firstName, lastName FROM authors" );

37

38 // process query results

39 ResultSetMetaData metaData = resultSet.getMetaData();

40 int numberOfColumns = metaData.getColumnCount();

41 System.out.println( "Authors Table of Books Database:" );

42

43 for ( int i = 1; i <= numberOfColumns; i++ )

44 System.out.printf( "%-8s\t", metaData.getColumnName( i ) );

45 System.out.println();

46

47 while ( resultSet.next() )

48 {

49 for ( int i = 1; i <= numberOfColumns; i++ )

50 System.out.printf( "%-8s\t", resultSet.getObject( i ) );

51 System.out.println();

52 } // end while

53 } // end try

54 catch ( SQLException sqlException )

55 {

56 sqlException.printStackTrace();

57 System.exit( 1 );

58 } // end catch

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

Catch SQLException, which is thrown if the query execution or ResultSet process fails

Page 68: 2005 Pearson Education, Inc. All rights reserved. 1 25 Accessing Databases with JDBC.

68

2005 Pearson Education, Inc. All rights reserved.

Outline

DisplayAuthors .java

(3 of 3)

Line 69

Lines 68-69

Program output

59 catch ( ClassNotFoundException classNotFound ) 60 { 61 classNotFound.printStackTrace(); 62 System.exit( 1 ); 63 } // end catch 64 finally // ensure statement and connection are closed properly 65 { 66 try 67 { 68 statement.close(); 69 connection.close(); 70 } // end try 71 catch ( Exception exception ) 72 { 73 exception.printStackTrace(); 74 System.exit( 1 ); 75 } // end catch 76 } // end finally 77 } // end main 78 } // end class DisplayAuthors Authors Table of Books Database: authorID firstName lastName 1 Harvey Deitel 2 Paul Deitel 3 Tem Nieto 4 Sean Santry

Close the Statement and the database Connection.

ClassNotFoundException is thrown if the class loader cannot locate the driver class

Page 69: 2005 Pearson Education, Inc. All rights reserved. 1 25 Accessing Databases with JDBC.

69

2005 Pearson Education, Inc. All rights reserved.

Fig. 25.26 | JDBC driver types.

Type Description

1 The JDBC-to-ODBC bridge driver connects Java programs to Microsoft ODBC (Open Database Connectivity) data sources. The Java 2 Software Development Kit from Sun Microsystems, Inc. includes the JDBC-to-ODBC Bridge driver (sun.jdbc.odbc.JdbcOdbcDriver). This driver typically requires the ODBC driver on the client computer and normally requires configuration of ODBC data sources. The Bridge driver was introduced primarily for development purposes, before other types of drivers were available, and should not be used for production applications.

2 Native-API, partly Java drivers enable JDBC programs to use database-specific APIs (normally written in C or C++) that allow client programs to access databases via the Java Native Interface (JNI). JNI is a bridge between a JVM and code written and compiled in a platform-specific language such as C or C++. Such code is known as native code. JNI enables Java applications to interact with native code. A Type 2 driver translates JDBC into database-specific calls. Type 2 drivers were introduced for reasons similar to the Type 1 ODBC bridge driver.

3 Pure Java client to server drivers take JDBC requests and translate them into a network protocol that is not database specific. These requests are sent to a server, which translates the database requests into a database-specific protocol.

4 Pure Java drivers implement database-specific network protocols, so that Java programs can connect directly to a database.

Page 70: 2005 Pearson Education, Inc. All rights reserved. 1 25 Accessing Databases with JDBC.

70

2005 Pearson Education, Inc. All rights reserved.

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.

Page 71: 2005 Pearson Education, Inc. All rights reserved. 1 25 Accessing Databases with JDBC.

71

2005 Pearson Education, Inc. All rights reserved.

Software Engineering Observation 25.5

On the Microsoft Windows platform, most databases support access via Open Database Connectivity (ODBC). ODBC is a technology developed by Microsoft to allow generic access to disparate database systems on the Windows platform (and some UNIX platforms). The JDBC-to-ODBC Bridge allows any Java program to access any ODBC data source. The driver is class JdbcOdbcDriver in package sun.jdbc.odbc.

Page 72: 2005 Pearson Education, Inc. All rights reserved. 1 25 Accessing Databases with JDBC.

72

2005 Pearson Education, Inc. All rights reserved.

Fig. 25.27 | Popular JDBC driver names and database URL.

RDBMS JDBC driver name Database URL format

MySQL com.mysql.jdbc.Driver jdbc:mysql://hostname/databaseName

ORACLE oracle.jdbc.driver.OracleDriver

jdbc:oracle:thin:@hostname:port Number:databaseName

DB2 COM.ibm.db2.jdbc.net.DB2Driver

jdbc:db2:hostname:portnumber/data baseName

Sybase com.sybase.jdbc.SybDriver jdbc:sybase:Tds:hostname:portnuber/databaseName

Page 73: 2005 Pearson Education, Inc. All rights reserved. 1 25 Accessing Databases with JDBC.

73

2005 Pearson Education, Inc. All rights reserved.

Software Engineering Observation 25.6

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.

Page 74: 2005 Pearson Education, Inc. All rights reserved. 1 25 Accessing Databases with JDBC.

74

2005 Pearson Education, Inc. All rights reserved.

Software Engineering Observation 25.7

Metadata enables programs to process ResultSet contents dynamically when detailed information about the ResultSet is not known in advance.

Page 75: 2005 Pearson Education, Inc. All rights reserved. 1 25 Accessing Databases with JDBC.

75

2005 Pearson Education, Inc. All rights reserved.

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.

Page 76: 2005 Pearson Education, Inc. All rights reserved. 1 25 Accessing Databases with JDBC.

76

2005 Pearson Education, Inc. All rights reserved.

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 linear search of the column names to locate the appropriate column.

Page 77: 2005 Pearson Education, Inc. All rights reserved. 1 25 Accessing Databases with JDBC.

77

2005 Pearson Education, Inc. All rights reserved.

Common Programming Error 25.9

Specifying column number 0 when obtaining values from a ResultSet causes a SQLException.

Page 78: 2005 Pearson Education, Inc. All rights reserved. 1 25 Accessing Databases with JDBC.

78

2005 Pearson Education, Inc. All rights reserved.

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.

Page 79: 2005 Pearson Education, Inc. All rights reserved. 1 25 Accessing Databases with JDBC.

79

2005 Pearson Education, Inc. All rights reserved.

Software Engineering Observation 25.8

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.

Page 80: 2005 Pearson Education, Inc. All rights reserved. 1 25 Accessing Databases with JDBC.

80

2005 Pearson Education, Inc. All rights reserved.

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

Page 81: 2005 Pearson Education, Inc. All rights reserved. 1 25 Accessing Databases with JDBC.

81

2005 Pearson Education, Inc. All rights reserved.

Outline

ResultSetTableModel.java

(1 of 8)

Line 17

Line 26

1 // Fig. 25.28: ResultSetTableModel.java

2 // A TableModel that supplies ResultSet data to a JTable.

3 import java.sql.Connection;

4 import java.sql.Statement;

5 import java.sql.DriverManager;

6 import java.sql.ResultSet;

7 import java.sql.ResultSetMetaData;

8 import java.sql.SQLException;

9 import javax.swing.table.AbstractTableModel;

10

11 // ResultSet rows and columns are counted from 1 and JTable

12 // rows and columns are counted from 0. When processing

13 // ResultSet rows or columns for use in a JTable, it is

14 // necessary to add 1 to the row or column number to manipulate

15 // the appropriate ResultSet column (i.e., JTable column 0 is

16 // ResultSet column 1 and JTable row 0 is ResultSet row 1).

17 public class ResultSetTableModel extends AbstractTableModel

18 {

19 private Connection connection;

20 private Statement statement;

21 private ResultSet resultSet;

22 private ResultSetMetaData metaData;

23 private int numberOfRows;

24

25 // keep track of database connection status

26 private boolean connectedToDatabase = false;

27

Class ResultSetTableModel extends class AbstractTableModel, which implements interface TableModel.

Instance variable keeps track of database connection status

Page 82: 2005 Pearson Education, Inc. All rights reserved. 1 25 Accessing Databases with JDBC.

82

2005 Pearson Education, Inc. All rights reserved.

Outline

ResultSetTableModel.java

(2 of 8)

Lines 30-31

Line 38

Lines 41-43

Line 46

Line 49

28 // constructor initializes resultSet and obtains its meta data object;

29 // determines number of rows

30 public ResultSetTableModel( String driver, String url,

31 String username, String password, String query )

32 throws SQLException, ClassNotFoundException

33 {

34 // load database driver class

35 Class.forName( driver );

36

37 // connect to database

38 connection = DriverManager.getConnection( url, username, password );

39

40 // create Statement to query database

41 statement = connection.createStatement(

42 ResultSet.TYPE_SCROLL_INSENSITIVE,

43 ResultSet.CONCUR_READ_ONLY );

44

45 // update database connection status

46 connectedToDatabase = true;

47

48 // set query and execute it

49 setQuery( query );

50 } // end constructor ResultSetTableModel

51

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.

Page 83: 2005 Pearson Education, Inc. All rights reserved. 1 25 Accessing Databases with JDBC.

83

2005 Pearson Education, Inc. All rights reserved.

Outline

ResultSetTableModel.java

(3 of 8)

Lines 53-73

Line 56

Line 62

Line 65

Line 72

52 // get class that represents column type

53 public Class getColumnClass( int column ) throws IllegalStateException

54 {

55 // ensure database connection is available

56 if ( !connectedToDatabase )

57 throw new IllegalStateException( "Not Connected to Database" );

58

59 // determine Java class of column

60 try

61 {

62 String className = metaData.getColumnClassName( column + 1 );

63

64 // return Class object that represents className

65 return Class.forName( className );

66 } // end try

67 catch ( Exception exception )

68 {

69 exception.printStackTrace();

70 } // end catch

71

72 return Object.class; // if problems occur above, assume type Object

73 } // end method getColumnClass

74

Override method getColumnClass to obtain a Class object that represents the superclass of all objects in a particular column

Verify database connection status

Obtains the fully qualified class name for the specified column.

Loads the class definition for the class and returns the corresponding Class object.

Returns the default type.

Page 84: 2005 Pearson Education, Inc. All rights reserved. 1 25 Accessing Databases with JDBC.

84

2005 Pearson Education, Inc. All rights reserved.

Outline

ResultSetTableModel.java

(4 of 8)

Lines 76-93

Line 85

Lines 96-113

75 // get number of columns in ResultSet

76 public int getColumnCount() throws IllegalStateException

77 {

78 // ensure database connection is available

79 if ( !connectedToDatabase )

80 throw new IllegalStateException( "Not Connected to Database" );

81

82 // determine number of columns

83 try

84 {

85 return metaData.getColumnCount();

86 } // end try

87 catch ( SQLException sqlException )

88 {

89 sqlException.printStackTrace();

90 } // end catch

91

92 return 0; // if problems occur above, return 0 for number of columns

93 } // end method getColumnCount

94

95 // get name of a particular column in ResultSet

96 public String getColumnName( int column ) throws IllegalStateException

97 {

98 // ensure database connection is available

99 if ( !connectedToDatabase )

100 throw new IllegalStateException( "Not Connected to Database" );

101

Override method getColumnCount to obtain the number of columns in the model’s underlying ResultSet

Obtains the number of columns in the ResultSet.

Override method getColumnName to obtain the name of the column in the model’s underlying ResultSet

Page 85: 2005 Pearson Education, Inc. All rights reserved. 1 25 Accessing Databases with JDBC.

85

2005 Pearson Education, Inc. All rights reserved.

Outline

ResultSetTableModel.java

(5 of 8)

Line 105

Lines 116-123

102 // determine column name

103 try

104 {

105 return metaData.getColumnName( column + 1 );

106 } // end try

107 catch ( SQLException sqlException )

108 {

109 sqlException.printStackTrace();

110 } // end catch

111

112 return ""; // if problems, return empty string for column name

113 } // end method getColumnName

114

115 // return number of rows in ResultSet

116 public int getRowCount() throws IllegalStateException

117 {

118 // ensure database connection is available

119 if ( !connectedToDatabase )

120 throw new IllegalStateException( "Not Connected to Database" );

121

122 return numberOfRows;

123 } // end method getRowCount

124

Obtains the column name from the ResultSet.

Override method getColumnCount to obtain the number of rows in the model’s underlying ResultSet

Page 86: 2005 Pearson Education, Inc. All rights reserved. 1 25 Accessing Databases with JDBC.

86

2005 Pearson Education, Inc. All rights reserved.

Outline

ResultSetTableModel.java

(6 of 8)

Lines 126-145

Line 136

Line 137

125 // obtain value in particular row and column

126 public Object getValueAt( int row, int column )

127 throws IllegalStateException

128 {

129 // ensure database connection is available

130 if ( !connectedToDatabase )

131 throw new IllegalStateException( "Not Connected to Database" );

132

133 // obtain a value at specified ResultSet row and column

134 try

135 {

136 resultSet.absolute( row + 1 );

137 return resultSet.getObject( column + 1 );

138 } // end try

139 catch ( SQLException sqlException )

140 {

141 sqlException.printStackTrace();

142 } // end catch

143

144 return ""; // if problems, return empty string object

145 } // end method getValueAt

146

147 // set new database query string

148 public void setQuery( String query )

149 throws SQLException, IllegalStateException

150 {

151 // ensure database connection is available

152 if ( !connectedToDatabase )

153 throw new IllegalStateException( "Not Connected to Database" );

154

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.

Page 87: 2005 Pearson Education, Inc. All rights reserved. 1 25 Accessing Databases with JDBC.

87

2005 Pearson Education, Inc. All rights reserved.

Outline

ResultSetTableModel.java

(7 of 8)

Line 156

Line 162

Line 163

Line 166

155 // specify query and execute it

156 resultSet = statement.executeQuery( query );

157

158 // obtain meta data for ResultSet

159 metaData = resultSet.getMetaData();

160

161 // determine number of rows in ResultSet

162 resultSet.last(); // move to last row

163 numberOfRows = resultSet.getRow(); // get row number

164

165 // notify JTable that model has changed

166 fireTableStructureChanged();

167 } // end method setQuery

168

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.

Page 88: 2005 Pearson Education, Inc. All rights reserved. 1 25 Accessing Databases with JDBC.

88

2005 Pearson Education, Inc. All rights reserved.

Outline

ResultSetTableModel.java

(8 of 8)

Lines 170-189

Line 172

Lines 178-179

Line 187

169 // close Statement and Connection

170 public void disconnectFromDatabase()

171 {

172 if ( !connectedToDatabase )

173 return;

174

175 // close Statement and Connection

176 try

177 {

178 statement.close();

179 connection.close();

180 } // end try

181 catch ( SQLException sqlException )

182 {

183 sqlException.printStackTrace();

184 } // end catch

185 finally // update database connection status

186 {

187 connectedToDatabase = false;

188 } // end finally

189 } // end method disconnectFromDatabase

190 } // end class ResultSetTableModel

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

Page 89: 2005 Pearson Education, Inc. All rights reserved. 1 25 Accessing Databases with JDBC.

89

2005 Pearson Education, Inc. All rights reserved.

Portability Tip 25.5

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.

Page 90: 2005 Pearson Education, Inc. All rights reserved. 1 25 Accessing Databases with JDBC.

90

2005 Pearson Education, Inc. All rights reserved.

Portability Tip 25.6

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.

Page 91: 2005 Pearson Education, Inc. All rights reserved. 1 25 Accessing Databases with JDBC.

91

2005 Pearson Education, Inc. All rights reserved.

Common Programming Error 25.11

Attempting to update a ResultSet when the database driver does not support updatable ResultSets causes SQLExceptions.

Page 92: 2005 Pearson Education, Inc. All rights reserved. 1 25 Accessing Databases with JDBC.

92

2005 Pearson Education, Inc. All rights reserved.

Fig. 25.29 | ResultSet constants for specifying ResultSet type.

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.

Page 93: 2005 Pearson Education, Inc. All rights reserved. 1 25 Accessing Databases with JDBC.

93

2005 Pearson Education, Inc. All rights reserved.

Fig. 25.30 | ResultSet constants for specifying result properties.

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).

Page 94: 2005 Pearson Education, Inc. All rights reserved. 1 25 Accessing Databases with JDBC.

94

2005 Pearson Education, Inc. All rights reserved.

Common Programming Error 25.12

Attempting to move the cursor backwards through a ResultSet when the database driver does not support backwards scrolling causes a SQLException.

Page 95: 2005 Pearson Education, Inc. All rights reserved. 1 25 Accessing Databases with JDBC.

95

2005 Pearson Education, Inc. All rights reserved.

Outline

DisplayQueryResults.java

(1 of 7)

Lines 22-25

1 // Fig. 25.31: DisplayQueryResults.java

2 // Display the contents of the Authors table in the

3 // Books database.

4 import java.awt.BorderLayout;

5 import java.awt.event.ActionListener;

6 import java.awt.event.ActionEvent;

7 import java.awt.event.WindowAdapter;

8 import java.awt.event.WindowEvent;

9 import java.sql.SQLException;

10 import javax.swing.JFrame;

11 import javax.swing.JTextArea;

12 import javax.swing.JScrollPane;

13 import javax.swing.ScrollPaneConstants;

14 import javax.swing.JTable;

15 import javax.swing.JOptionPane;

16 import javax.swing.JButton;

17 import javax.swing.Box;

18

19 public class DisplayQueryResults extends JFrame

20 {

21 // JDBC driver and database URL

22 static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";

23 static final String DATABASE_URL = "jdbc:mysql://localhost/books";

24 static final String USERNAME= "jhtp6";

25 static final String PASSWORD= "jhtp6";

26

Declare the database driver class name, database URL, username and password for accessing the database

Page 96: 2005 Pearson Education, Inc. All rights reserved. 1 25 Accessing Databases with JDBC.

96

2005 Pearson Education, Inc. All rights reserved.

Outline

DisplayQueryResults.java

(2 of 7)

Line 28

Line 30

Lines 42-43

27 // default query selects all rows from authors table

28 static final String DEFAULT_QUERY = "SELECT * FROM authors";

29

30 private ResultSetTableModel tableModel;

31 private JTextArea queryArea;

32

33 // create ResultSetTableModel and GUI

34 public DisplayQueryResults()

35 {

36 super( "Displaying Query Results" );

37

38 // create ResultSetTableModel and display database table

39 try

40 {

41 // create TableModel for results of query SELECT * FROM authors

42 tableModel = new ResultSetTableModel( JDBC_DRIVER, DATABASE_URL,

43 USERNAME, PASSWORD, DEFAULT_QUERY );

44

45 // set up JTextArea in which user types queries

46 queryArea = new JTextArea( DEFAULT_QUERY, 3, 100 );

47 queryArea.setWrapStyleWord( true );

48 queryArea.setLineWrap( true );

49

50 JScrollPane scrollPane = new JScrollPane( queryArea,

51 ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,

52 ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER );

53

54 // set up JButton for submitting queries

55 JButton submitButton = new JButton( "Submit Query" );

56

Declare the default query

Declare tableModel to be a reference to ResultSetTableModel

Create TableModel for results of default query “SELECT * FROM authors”

Page 97: 2005 Pearson Education, Inc. All rights reserved. 1 25 Accessing Databases with JDBC.

97

2005 Pearson Education, Inc. All rights reserved.

Outline

DisplayQueryResults.java

(3 of 7)

Line 64

Lines 71-110

Line 81

57 // create Box to manage placement of queryArea and 58 // submitButton in GUI 59 Box box = Box.createHorizontalBox(); 60 box.add( scrollPane ); 61 box.add( submitButton ); 62 63 // create JTable delegate for tableModel 64 JTable resultTable = new JTable( tableModel ); 65 66 // place GUI components on content pane 67 add( box, BorderLayout.NORTH ); 68 add( new JScrollPane( resultTable ), BorderLayout.CENTER ); 69 70 // create event listener for submitButton 71 submitButton.addActionListener( 72 73 new ActionListener() 74 { 75 // pass query to table model 76 public void actionPerformed( ActionEvent event ) 77 { 78 // perform a new query 79 try 80 { 81 tableModel.setQuery( queryArea.getText() ); 82 } // end try 83 catch ( SQLException sqlException ) 84 { 85 JOptionPane.showMessageDialog( null, 86 sqlException.getMessage(), "Database error", 87 JOptionPane.ERROR_MESSAGE ); 88

Create JTable delegate for tableModel

Register an event handler for the submitButton that the user clicks to submit a query to the database

Invoke ResultSetTableModel method setQuery to execute the new query

Page 98: 2005 Pearson Education, Inc. All rights reserved. 1 25 Accessing Databases with JDBC.

98

2005 Pearson Education, Inc. All rights reserved.

Outline

DisplayQueryResults.java

(4 of 7)

Line 103

89 // try to recover from invalid user query

90 // by executing default query

91 try

92 {

93 tableModel.setQuery( DEFAULT_QUERY );

94 queryArea.setText( DEFAULT_QUERY );

95 } // end try

96 catch ( SQLException sqlException2 )

97 {

98 JOptionPane.showMessageDialog( null,

99 sqlException2.getMessage(), "Database error",

100 JOptionPane.ERROR_MESSAGE );

101

102 // ensure database connection is closed

103 tableModel.disconnectFromDatabase();

104

105 System.exit( 1 ); // terminate application

106 } // end inner catch

107 } // end outer catch

108 } // end actionPerformed

109 } // end ActionListener inner class

110 ); // end call to addActionListener

111

112 setSize( 500, 250 ); // set window size

113 setVisible( true ); // display window

114 } // end try

115 catch ( ClassNotFoundException classNotFound )

Ensure that the database connection is closed

Page 99: 2005 Pearson Education, Inc. All rights reserved. 1 25 Accessing Databases with JDBC.

99

2005 Pearson Education, Inc. All rights reserved.

Outline

DisplayQueryResults.java

(5 of 7)

Line 129

116 {

117 JOptionPane.showMessageDialog( null,

118 "MySQL driver not found", "Driver not found",

119 JOptionPane.ERROR_MESSAGE );

120

121 System.exit( 1 ); // terminate application

122 } // end catch

123 catch ( SQLException sqlException )

124 {

125 JOptionPane.showMessageDialog( null, sqlException.getMessage(),

126 "Database error", JOptionPane.ERROR_MESSAGE );

127

128 // ensure database connection is closed

129 tableModel.disconnectFromDatabase();

130

131 System.exit( 1 ); // terminate application

132 } // end catch

133

134 // dispose of window when user quits application (this overrides

135 // the default of HIDE_ON_CLOSE)

136 setDefaultCloseOperation( DISPOSE_ON_CLOSE );

137

138 // ensure database connection is closed when user quits application

139 addWindowListener(

140

Ensure that the database connection is closed

Page 100: 2005 Pearson Education, Inc. All rights reserved. 1 25 Accessing Databases with JDBC.

100

2005 Pearson Education, Inc. All rights reserved.

Outline

DisplayQueryResults.java

(6 of 7)

Lines 144-148

141 new WindowAdapter()

142 {

143 // disconnect from database and exit when window has closed

144 public void windowClosed( WindowEvent event )

145 {

146 tableModel.disconnectFromDatabase();

147 System.exit( 0 );

148 } // end method windowClosed

149 } // end WindowAdapter inner class

150 ); // end call to addWindowListener

151 } // end DisplayQueryResults constructor

152

153 // execute application

154 public static void main( String args[] )

155 {

156 new DisplayQueryResults();

157 } // end main

158 } // end class DisplayQueryResults

Ensure that the database connection is closed when window has closed

Page 101: 2005 Pearson Education, Inc. All rights reserved. 1 25 Accessing Databases with JDBC.

101

2005 Pearson Education, Inc. All rights reserved.

Outline

DisplayQueryResults.java

(7 of 7)

Program output

Page 102: 2005 Pearson Education, Inc. All rights reserved. 1 25 Accessing Databases with JDBC.

102

2005 Pearson Education, Inc. All rights reserved.

25.9 Stored Procedure

• Stored procedures– Store SQL statements in a database

– Invoke SQL statements by programs accessing the database

• Interface CallableStatement– Receive arguments

– Output parameters

Page 103: 2005 Pearson Education, Inc. All rights reserved. 1 25 Accessing Databases with JDBC.

103

2005 Pearson Education, Inc. All rights reserved.

Portability Tip 25.7

Although the syntax for creating stored procedures differs across database management systems, interface CallableStatement provides a uniform interface for specifying input and output parameters for stored procedures and for invoking stored procedures.

Page 104: 2005 Pearson Education, Inc. All rights reserved. 1 25 Accessing Databases with JDBC.

104

2005 Pearson Education, Inc. All rights reserved.

Portability Tip 25.8

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.

Page 105: 2005 Pearson Education, Inc. All rights reserved. 1 25 Accessing Databases with JDBC.

105

2005 Pearson Education, Inc. All rights reserved.

15.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

Page 106: 2005 Pearson Education, Inc. All rights reserved. 1 25 Accessing Databases with JDBC.

106

2005 Pearson Education, Inc. All rights reserved.

15.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

Page 107: 2005 Pearson Education, Inc. All rights reserved. 1 25 Accessing Databases with JDBC.

107

2005 Pearson Education, Inc. All rights reserved.

Outline

JdbcRowSetTest.java

(1 of 3)

Line 27

Line 17

Line 28

Line 29

Line 30

Line 31

1 // Fig. 25.32: JdbcRowSetTest.java 2 // Displaying the contents of the authors table using JdbcRowSet. 3 import java.sql.ResultSetMetaData; 4 import java.sql.SQLException; 5 import javax.sql.rowset.JdbcRowSet; 6 import com.sun.rowset.JdbcRowSetImpl; // Sun’s JdbcRowSet implementation 7 8 public class JdbcRowSetTest 9 { 10 // JDBC driver name and database URL 11 static final String JDBC_DRIVER = "com.mysql.jdbc.Driver"; 12 static final String DATABASE_URL = "jdbc:mysql://localhost/books"; 13 static final String USERNAME = "jhtp6"; 14 static final String PASSWORD = "jhtp6"; 15 16 // constructor connects to database, queries database, processes 17 // results and displays results in window 18 public JdbcRowSetTest() 19 { 20 // connect to database books and query database 21 try 22 { 23 Class.forName( JDBC_DRIVER ); // load database driver class 24 25 // specify properties of JdbcRowSet 26 JdbcRowSet rowSet = new JdbcRowSetImpl(); 27 rowSet.setUrl( DATABASE_URL ); // set database URL 28 rowSet.setUsername( USERNAME ); // set username 29 rowSet.setPassword( PASSWORD ); // set password 30 rowSet.setCommand( "SELECT * FROM authors" ); // set query 31 rowSet.execute(); // execute query 32

Use Sun’s reference implementation of JdbcRowSet interface (JdbcRowSetImpl) to create a JdbcRowSet object

Invoke JdbcRowSet method setUrl to specify the database URLInvoke JdbcRowSet method setUsername to specify the usernameInvoke JdbcRowSet method setUsername to specify the passwordInvoke JdbcRowSet method

setCommand to specify the queryInvoke JdbcRowSet method execute to execute the query

Page 108: 2005 Pearson Education, Inc. All rights reserved. 1 25 Accessing Databases with JDBC.

108

2005 Pearson Education, Inc. All rights reserved.

Outline

JdbcRowSetTest.java

(2 of 3)

33 // process query results 34 ResultSetMetaData metaData = rowSet.getMetaData(); 35 int numberOfColumns = metaData.getColumnCount(); 36 System.out.println( "Authors Table of Books Database:" ); 37 38 // display rowset header 39 for ( int i = 1; i <= numberOfColumns; i++ ) 40 System.out.printf( "%-8s\t", metaData.getColumnName( i ) ); 41 System.out.println(); 42 43 // display each row 44 while ( rowSet.next() ) 45 { 46 for ( int i = 1; i <= numberOfColumns; i++ ) 47 System.out.printf( "%-8s\t", rowSet.getObject( i ) ); 48 System.out.println(); 49 } // end while 50 } // end try 51 catch ( SQLException sqlException ) 52 { 53 sqlException.printStackTrace(); 54 System.exit( 1 ); 55 } // end catch 56 catch ( ClassNotFoundException classNotFound ) 57 { 58 classNotFound.printStackTrace(); 59 System.exit( 1 ); 60 } // end catch 61 } // end DisplayAuthors constructor 62

Page 109: 2005 Pearson Education, Inc. All rights reserved. 1 25 Accessing Databases with JDBC.

109

2005 Pearson Education, Inc. All rights reserved.

Outline

JdbcRowSetTest.java

(3 of 3)

Program output

63 // launch the application

64 public static void main( String args[] )

65 {

66 JdbcRowSetTest window = new JdbcRowSetTest();

67 } // end main

68 } // end class JdbcRowSetTest Authors Table of Books Database: authorID firstName lastName 1 Harvey Deitel 2 Paul Deitel 3 Tem Nieto 4 Sean Santry