Download ResultSet

Document related concepts

Oracle Database wikipedia , lookup

Entity–attribute–value model wikipedia , lookup

Microsoft SQL Server wikipedia , lookup

Ingres (database) wikipedia , lookup

Concurrency control wikipedia , lookup

Extensible Storage Engine wikipedia , lookup

Functional Database Model wikipedia , lookup

SQL wikipedia , lookup

Database wikipedia , lookup

Microsoft Jet Database Engine wikipedia , lookup

PL/SQL wikipedia , lookup

Open Database Connectivity wikipedia , lookup

Versant Object Database wikipedia , lookup

Clusterpoint wikipedia , lookup

ContactPoint wikipedia , lookup

Relational model wikipedia , lookup

Database model wikipedia , lookup

Transcript
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.
 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
 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
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.
8
Fig. 25.1 | Employee table sample data.
 1992-2007 Pearson Education, Inc. All rights reserved.
9
Fig. 25.2 | Result of selecting distinct Department and Location
data from table Employee.
 1992-2007 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
 2005 Pearson Education, Inc. All rights reserved.
11
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.
12
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.
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
 2005 Pearson Education, Inc. All rights reserved.
14
Column
Description
authorID
The author’s ID number, a foreign key to the authors table.
isbn
The ISBN for a book, a foreign key to the titles table.
Fig. 25.5 | authorISBN table from the books database.
 1992-2007 Pearson Education, Inc. All rights reserved.
15
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.
16
Column
Description
isbn
ISBN of the book (a string). The table’s primary key. ISBN is an
abbreviation for “International Standard Book Number”—a
numbering scheme that publishers use to give every book a unique
identification number.
title
Title of the book (a string).
editionNumber
Edition number of the book (an integer).
copyright
Copyright year of the book (a string).
Fig. 25.7 | titles table from the books database.
 1992-2007 Pearson Education, Inc. All rights reserved.
17
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.
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
 2005 Pearson Education, Inc. All rights reserved.
19
Fig. 25.9 | Table relationships in the books database.
 1992-2007 Pearson Education, Inc. All rights reserved.
20
25.4 SQL
• SQL keywords
– SQL queries and statements
 2005 Pearson Education, Inc. All rights reserved.
21
SQL keyword
Description
SELECT
Retrieves data from one or more tables.
FROM
Tables involved in the query. Required in every SELECT.
WHERE
Criteria for selection that determine the rows to be retrieved,
deleted or updated. Optional in a SQL query or a SQL statement.
GROUP BY
Criteria for grouping rows. Optional in a SELECT query.
ORDER BY
Criteria for ordering rows. Optional in a SELECT query.
INNER JOIN
Merge rows from multiple tables.
INSERT
Insert rows into a specified table.
UPDATE
Update rows in a specified table.
DELETE
Delete rows from a specified table.
Fig. 25.10 | SQL query keywords.
 1992-2007 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
 2005 Pearson Education, Inc. All rights reserved.
23
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.
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
 2005 Pearson Education, Inc. All rights reserved.
25
title
editionNumber
copyright
Visual C# How to Program
2
2006
Visual Basic 2005 How to Program
3
2006
Java How to Program
7
2007
C How to Program
5
2007
Fig. 25.12 | Sampling of titles with copyrights after 2005 from table titles.
 1992-2007 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%’
 2005 Pearson Education, Inc. All rights reserved.
27
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.
28
25.4.2 WHERE Clause (Cont.)
• SELECT authorID, firstName, lastName
FROM authors
WHERE lastName LIKE ‘_i%’
 2005 Pearson Education, Inc. All rights reserved.
29
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.
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
 2005 Pearson Education, Inc. All rights reserved.
31
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.
32
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.
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
 2005 Pearson Education, Inc. All rights reserved.
34
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.
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
 2005 Pearson Education, Inc. All rights reserved.
36
isbn
title
edition
-Number
copy-right
0132404168
C How to Program
5
2007
0131857576
C++ How to Program
5
2005
0131450913
Internet and World Wide Web How to Program 3
2004
0132222205
Java How to Program
7
2007
0131869000
Visual Basic 2005 How to Program
3
2006
013152539
Visual C# How to Program
2
2006
Fig. 25.18 | Sampling of books from table titles whose titles end with
How to Program in ascending order by title.
 1992-2007 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
 2005 Pearson Education, Inc. All rights reserved.
38
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
0131450913
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.
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’ )
 2005 Pearson Education, Inc. All rights reserved.
40
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.
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’
 2005 Pearson Education, Inc. All rights reserved.
42
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.
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’
 2005 Pearson Education, Inc. All rights reserved.
44
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.
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/generalinstallation-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.
 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.
 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
 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;
 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;
 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
 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
 2005 Pearson Education, Inc. All rights reserved.
1
2
// Fig. 25.23: DisplayAuthors.java
// Displaying the contents of the authors table.
3
4
import java.sql.Connection;
import java.sql.Statement;
5
6
import java.sql.DriverManager;
import java.sql.ResultSet;
7
8
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
52
Outline
Imports for the JDBC classes and
interfaces from package java.sql
DisplayAuthors .
java
9
10 public class DisplayAuthors
(1 of 3 )
11 {
12
13
// JDBC driver name and database URL
static final String 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
20
21
22
Connection connection = null; // manages connection
Statement statement = null; // query statement
ResultSet resultSet = null; // manages results
23
24
// connect to database books and query database
try
25
26
{
27
28
// load the driver class
Class.forName( DRIVER );
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.
 1992-2007 Pearson Education, Inc. All rights reserved.
// establish connection to database
connection =
29
30
DriverManager.getConnection( DATABASE_URL, "jhtp7", "jhtp7" );
31
32
33
53
// create Statement for querying database
statement = connection.createStatement();
34
35
36
37
38
39
Invokes ConnectionDisplayAuthors
method
.
createStatement to java
obtain an object
// query database
Use theinterface
Statement
object’s
that implements
Statement.
resultSet = statement.executeQuery(
executeQuery
to
(2 ofmethod
3)
"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.getColumnCount();
System.out.println( "Authors Table of Books Database:\n" );method getColumnCount
to retrieve the number of
columns in the ResultSet.
for ( int i = 1; i <= numberOfColumns; i++ )
Obtain column
System.out.printf( "%-8s\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
{
40
41
42
43
44
45
46
47
48
49
50
51
for ( int i = 1; i <= numberOfColumns; i++ )
52
53
System.out.printf( "%-8s\t", resultSet.getObject( i ) );
System.out.println();
} // end while
54
55
Initialize a
Outline
Connection
reference
called connection.
}
Extract the contents
of one column in the
current row
// end try
 1992-2007 Pearson Education, Inc. All rights reserved.
56
57
58
catch ( SQLException sqlException )
{
sqlException.printStackTrace();
59
60
61
62
63
} // end catch
catch ( ClassNotFoundException classNotFound )
{
classNotFound.printStackTrace();
} // end catch
64
65
66
67
68
69
finally // ensure resultSet, statement and connection
{
try
{
resultSet.close();
Close the Statement
statement.close();
70
71
72
connection.close();
} // end try
catch ( Exception exception )
73
74
75
{
Catch SQLException, which
Outline
is thrown if the query execution
or ResultSet process fails
54
DisplayAuthors
.
ClassNotFoundException
is
java
thrown if the class loader
cannot
locate the driver class
are
closed
(3 of 3 )
and
the database Connection.
exception.printStackTrace();
} // end catch
76
} // end finally
77
} // 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.
55
RDBMS
Database URL format
MySQL
jdbc:mysql://hostname:portNumber/databaseName
ORACLE
jdbc:oracle:thin:@hostname:portNumber:databaseName
DB2
jdbc:db2:hostname:portNumber/databaseName
Java DB/Apache Derby
jdbc:derby:dataBaseName (embedded)
jdbc:derby://hostname:portNumber/databaseName (network)
Microsoft SQL Server
jdbc:sqlserver://hostname:portNumber;databaseName=dataBaseName
Sybase
jdbc:sybase:Tds:hostname:portNumber/databaseName
Fig. 25.24 | Popular JDBC database URL formats.
 1992-2007 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
 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
6
import java.sql.DriverManager;
import java.sql.ResultSet;
7
8
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
57
Outline
ResultSetTable
Model.java
9 import javax.swing.table.AbstractTableModel;
10
(1 of 7 )
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;
Class ResultSetTableModel extends
21
private ResultSet resultSet;
class AbstractTableModel, which
22
private ResultSetMetaData metaData;
23
private int numberOfRows;
implements interface TableModel.
24
25
26
27
// keep track of database connection status
private boolean connectedToDatabase = false;
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 ResultSetTableModel( String driver, String url, String Constructor
username,
String password, String query
)
Establishes
a connection
throws SQLException, ClassNotFoundException
to the database.
31
32
33
34
35
{
Class.forName( driver );
// connect to database
connection = DriverManager.getConnection( url, username, password );
39
40
41
42
statement = connection.createStatement(
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY );
43
44
45
// update database connection status
connectedToDatabase = true;
46
47
48
49
Outline
accepts five String
arguments—the driver class
name, the database URL, the
ResultSetTable
username, the password
and the
Model.java
default query to perform
36
37
38
// create Statement to query database
58
(2 of 7 )
Invokes Connection
method createStatement to
create a Statement object.
Indicate that connect to
database is successful
// set query and execute it Invokes ResultSetTableModel
setQuery( query );
method setQuery to perform
} // end constructor ResultSetTableModel
the default query.
 1992-2007 Pearson Education, Inc. All rights reserved.
50
51
// get class that represents column type
public Class getColumnClass( int column ) throws IllegalStateException
52
53
{
54
Verify database
Override method getColumnClass to obtain
connection status
IllegalStateException( "Not Connected to Database" );
ResultSetTable
a Class object that represents
the superclass
Model.java
of all objects in a particular column
Java class of column
if ( !connectedToDatabase )
throw new
56
57
58
// determine
try
61
62
63
Outline
// ensure database connection is available
55
59
60
59
{
String className = metaData.getColumnClassName( column
(3 of 7 ) class
Obtains the fully qualified
+name
1 ); for the specified column.
// return Class object that represents className
Loads
return Class.forName( className );
64
} // end try
65
66
67
68
69
catch ( Exception exception )
{
exception.printStackTrace();
} // end catch
the class definition for the class and
returns the corresponding Class object.
Returns the
default type.
70
71
return Object.class; // if problems occur above, assume type Object
} // end method getColumnClass
72
73
// get number of columns in ResultSet
74
75
76
77
78
public int getColumnCount() throws IllegalStateException
{
// ensure database connection is available
if ( !connectedToDatabase )
method
throw new IllegalStateException( Override
"Not Connected
togetColumnCount
Database" );
79
to obtain the number of columns in the
model’s underlying ResultSet
 1992-2007 Pearson Education, Inc. All rights reserved.
80
81
// determine number of columns
try
82
83
{
84
} // end try
85
catch ( SQLException sqlException )
86
87
88
{
60
Obtains the number of
columns in the ResultSet.
return metaData.getColumnCount();
ResultSetTable
Model.java
sqlException.printStackTrace();
} // end catch
89
90
Outline
(4 of 7 )
return 0; // if problems occur above, return 0 for number of columns
91
92
93
} // end method getColumnCount
94
public String getColumnName( int column ) throws IllegalStateException
95
96
97
98
99
{
// get name of a particular column in ResultSet
// ensure database connection is available
if ( !connectedToDatabase )
method
getColumnName
throw new IllegalStateException( "NotOverride
Connected
to Database"
);
100
101
// determine column name
try
102
103
{
104
105
106
107
108
} // end try
catch ( SQLException sqlException )
{
sqlException.printStackTrace();
} // end catch
to obtain the name of the column in
the model’s underlying ResultSet
return metaData.getColumnName( column + 1 );
Obtains the column name
from the ResultSet.
109
 1992-2007 Pearson Education, Inc. All rights reserved.
return ""; // if problems, return empty string for column name
110
111
112
} // end method getColumnName
113
// return number of rows in ResultSet
114
public int getRowCount() throws IllegalStateException
115
116
117
118
119
{
120
121
return numberOfRows;
} // end method getRowCount
122
123
124
125
126
// obtain value in particular row and column
public Object getValueAt( int row, int column )
throws IllegalStateException
{
Outline
// ensure database connection is available
if ( !connectedToDatabase )
Override
method
getColumnCount
throw new IllegalStateException(
"Not
Connected
to Database" );
to obtain the number of rows in the
model’s underlying ResultSet
127
128
129
130
// ensure database connection
is available
Override
method getValueAt to obtain
if ( !connectedToDatabase )
the Object in a particular row and column
throw new IllegalStateException( "Not Connected to Database" );
131
132
133
// obtain a value at specified ResultSet row and column
try
{
134
135
136
61
ResultSetTable
Model.java
(5 of 7 )
of the model’s underlying ResultSet
Uses ResultSet method absolute to position
ResultSet cursor at a specific row.
resultSet.absolute( row + 1 );
the
return resultSet.getObject( column + 1 );
} // 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.
137
138
catch ( SQLException sqlException )
{
139
140
sqlException.printStackTrace();
} // end catch
62
Outline
141
return ""; // if problems, return empty string object
142
143
144
145
} // end method getValueAt
146
147
public void setQuery( String query )
throws SQLException, IllegalStateException
148
149
150
{
151
152
153
154
155
156
// set new database query string
(6 of 7 )
// ensure database connection is available
if ( !connectedToDatabase )
throw new IllegalStateException( "Not Connected to Database" );
// specify query and execute it
resultSet = statement.executeQuery( query );
Executes the query to
obtain a new ResultSet.
// obtain meta data for ResultSet
Uses ResultSet method last to
position the ResultSet cursor at
ResultSet the last row in the ResultSet.
157
158
metaData = resultSet.getMetaData();
159
160
// determine number of rows in
resultSet.last(); // move to last row
161
162
163
164
165
numberOfRows = resultSet.getRow(); // get row number
166
ResultSetTable
Model.java
// notify JTable that model has changed
fireTableStructureChanged();
} // 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
has Education,
changed.Inc. All rights reserved.
 1992-2007
Pearson
167
// close Statement and Connection
168
169
public void disconnectFromDatabase()
{
170
171
63
Verify whether the connection
is already terminated
Method disconnectFromDatabase
Statement and Connection
implement an appropriate termination method
for class ResultSetTableModel
if ( connectedToDatabase )
{
172
173
174
175
// close
try
{
resultSet.close();
176
177
178
179
180
statement.close();
connection.close();
} // end try
catch ( SQLException sqlException )
{
181
182
183
184
185
186
sqlException.printStackTrace();
} // end catch
finally // update database connection status
{
connectedToDatabase = false;
} // end finally
187
188
189 }
Outline
} // end if
} // end method disconnectFromDatabase
// end class ResultSetTableModel
ResultSetTable
Model.java
Close the Statement and Connection
if a7 )
(7 of
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
 1992-2007 Pearson Education, Inc. All rights reserved.
64
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.
65
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.
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
 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
 2005 Pearson Education, Inc. All rights reserved.
68
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
5
6
7
8
import java.sql.SQLException;
import javax.sql.rowset.JdbcRowSet;
import com.sun.rowset.JdbcRowSetImpl; // Sun's JdbcRowSet implementation
69
public class JdbcRowSetTest
9 {
10
// JDBC driver name and database URL
11
12
static final String DRIVER = "com.mysql.jdbc.Driver";
static final String DATABASE_URL = "jdbc:mysql://localhost/books";
13
static final String USERNAME = "jhtp7";
14
15
16
static final String PASSWORD = "jhtp7";
// constructor connects to database, queries database, processes
17
18
// results and displays results in window
public JdbcRowSetTest()
19
20
{
Outline
JdbcRowSetTest .
java
(1 of 3 )
// connect to database books and query database
21
try
22
23
24
{
Class.forName( DRIVER );
 1992-2007 Pearson Education, Inc. All rights reserved.
25
26
// specify properties of JdbcRowSet
JdbcRowSet rowSet = new JdbcRowSetImpl();
70
29
30
31
32
Use Sun’s reference
Invoke
JdbcRowSet
method Outline
rowSet.setUrl( DATABASE_URL ); // set database URL implementation of JdbcRowSet
Invoke JdbcRowSet
setUrl
to specify(JdbcRowSetImpl)
the method
database URL
rowSet.setUsername( USERNAME ); // set username
interface
to
Invoke
JdbcRowSet
method
setUsername
to
specify
the
username
rowSet.setPassword( PASSWORD ); // set password
JdbcRowSet
method
createInvoke
a to
JdbcRowSet
object
setUsername
specify
the password
rowSet.setCommand( "SELECT * FROM authors" ); // set query
setCommand
to JdbcRowSetTest
specify the query .
Invoke JdbcRowSet
method
rowSet.execute(); // execute query
java
execute to execute the query
33
34
// process query results
ResultSetMetaData metaData = rowSet.getMetaData();
35
36
int numberOfColumns = metaData.getColumnCount();
System.out.println( "Authors Table of Books Database:\n" );
27
28
(2 of 3 )
37
38
39
40
41
// display rowset header
for ( int i = 1; i <= numberOfColumns; i++ )
System.out.printf( "%-8s\t", metaData.getColumnName( i ) );
System.out.println();
42
43
44
45
46
47
48
// display each row
while ( rowSet.next() )
{
for ( int i = 1; i <= numberOfColumns; i++ )
System.out.printf( "%-8s\t", rowSet.getObject( i ) );
System.out.println();
49
50
51
52
} // end while
53
// close the underlying ResultSet, Statement and Connection
rowSet.close();
} // end try
 1992-2007 Pearson Education, Inc. All rights reserved.
54
catch ( SQLException sqlException )
55
{
56
57
58
sqlException.printStackTrace();
System.exit( 1 );
} // end catch
59
catch ( ClassNotFoundException classNotFound )
60
61
62
{
63
} // end catch
classNotFound.printStackTrace();
System.exit( 1 );
64
65
} // end DisplayAuthors constructor
66
67
// launch the application
public static void main( String args[] )
71
Outline
JdbcRowSetTest .
java
(3 of 3 )
68
{
69
JdbcRowSetTest application = new JdbcRowSetTest();
70
} // 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.