Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

AhmadLang / Java, How To Program, 2004

.pdf
Скачиваний:
626
Добавлен:
31.05.2015
Размер:
51.82 Mб
Скачать

15

16// constructor connects to database, queries database, processes

17// results and displays results in window

18public JdbcRowSetTest()

19{

20// connect to database books and query database

21try

22{

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

25// specify properties of JdbcRowSet

26JdbcRowSet rowSet = new JdbcRowSetImpl();

27rowSet.setUrl( DATABASE_URL ); // set database URL

28rowSet.setUsername( USERNAME ); // set username

29rowSet.setPassword( PASSWORD ); // set password

30rowSet.setCommand( "SELECT * FROM authors" ); // set query

31rowSet.execute(); // execute query

32

33// process query results

34ResultSetMetaData metaData = rowSet.getMetaData();

35int numberOfColumns = metaData.getColumnCount();

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

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

44while ( 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

51catch ( SQLException sqlException )

52{

53sqlException.printStackTrace();

54System.exit( 1 );

55} // end catch

56catch ( ClassNotFoundException classNotFound )

57{

58classNotFound.printStackTrace();

59System.exit( 1 );

60} // end catch

61} // end DisplayAuthors constructor

62

63// launch the application

64public static void main( String args[] )

65{

66JdbcRowSetTest 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

 

 

 

[Page 1227]

Line 26 uses Sun's reference implementation of the JdbcRowSet interface, JdbcRowSetImpl from package com.sun.rowset, to create a JdbcRowSet object. Package com.sun.rowset provides implementations of the interfaces in package javax.sql.rowset. We used class JdbcRowSetImpl here to demonstrate the capability of the JdbcRowSet interface. Some databases may provide their own RowSet implementations.

Line 27 invokes JdbcRowSet method setUrl to specify the database URL, which is then used by the DriverManager to establish a connection. Line 28 invokes JdbcRowSet method setUsername to specify the username, which is then used by the DriverManagger to establish a connection. Line 29 invokes JdbcRowSet method setPassword to specify the password, which is then used by the DriverManager to establish a connection. Line 30 invokes JdbcRowSet method setCommand to specify the SQL query. Line 31 invokes JdbcRowSet method execute to execute the SQL query. Method execute performs four actionsit establishes a Connection, prepares the query Statement, executes the query and stores the ResultSet returned by query. The Connection, Statement and ResultSet are encapsulated in the JdbcRowSet object. The remaining code is almost identical to Fig. 25.25, except that line 34 obtains a ResultSetMetaData object from the JdbcRowSet, line 44 uses the JdbcRowSet's next method to get the next row of the result, and line 47uses the JdbcRowSet's getObject method to obtain a column's value. Note that the output of this application is exactly the same as that of Fig. 25.25.

In this chapter, you learned basic database concepts, how to interact with data in a database using SQL and how to use JDBC to allow Java applications to manipulate database data. You learned the explicit steps for obtaining a Connection to the database, creating a Statement to interact with the database's data, executing the statement and processing the results. Finally you saw how to use a RowSet to simplify the process of connecting to a database and creating statements. In the next chapter, you will learn about servlets, which are Java programs that enhance a Web Server's capabilities. Servlets sometimes use JDBC to interact with databases on behalf of users who make requests via Web browsers.

[Page 1227 (continued)]

25.11. Wrap-Up

This chapter introduced the SQL and the JDBC API. You learned basic SQL to retrieve data from and update data in a database. You examined the contents of a sample database and learned how to set it up for use with the MySQL database management system. You also learned how to access and manipulate the MySQL database via the JDBC API. Then, you learned the new RowSet interface introduced in J2SE 5.0. In the next chapter, we demonstrate how to build Web applications using Java servlets. We also introduce the concept of a three-tier application, in which an application is divided into three pieces that can reside on the same computer or can be distributed among separate computers across a network, such as the Internet.

[Page 1227 (continued)]

25.12. Internet and Web Resources

java.sun.com/products/jdbc

Sun Microsystems, Inc.'s JDBC home page.

java.sun.com/docs/books/tutorial/jdbc/index.html

The Java Tutorial 's JDBC track.

industry.java.sun.com/products/jdbc/drivers

Sun Microsystems search engine for locating JDBC drivers.

[Page 1228]

www.sql.org

This SQL portal provides links to many resources, including SQL syntax, tips, tutorials, books, magazines, discussion groups, companies with SQL services, SQL consultants and free software.

java.sun.com/j2se/5.0/docs/guide/jdbc/index.html

Sun Microsystems JDBC API documentation.

java.sun.com/products/jdbc/faq.html

Sun Microsystems FAQs on JDBC.

www.jguru.com/faq/JDBC

The JGuru JDBC FAQs.

www.mysql.com

This site is the MySQL database home page. You can download the latest versions of MySQL and MySQL Connector/J and access their online documentation.

www.mysql.com/products/mysql

Introduction to the MySQL database server and links to its documentation and download sites.

dev.mysql.com/doc/mysql/en/index.html

MySQL reference manual.

dev.mysql.com/doc/connector/j/en/index.html

MySQL Connector/J documentation, including the installation instructions and examples.

java.sun.com/j2se/5.0/docs/guide/jdbc/getstart/rowsetImpl.html

Overviews the RowSet interface and its subinterfaces. This site also discusses the reference implementations of these interfaces from Sun and their usage.

developer.java.sun.com/developer/Books/JDBCTutorial/chapter5.html

Chapter 5 (RowSet Tutorial) of the book The JDBC 2.0 API Tutorial and Reference, Second Edition.

[Page 1228 (continued)]

Recommended Readings

Ashmore, D. C. "Best Practices for JDBC Programming." Java Developers Journal, 5: no. 4 (2000): 4254.

Blaha, M. R., W. J. Premerlani and J. E. Rumbaugh. "Relational Database Design Using an ObjectOriented Methodology." Communications of the ACM, 31: no. 4 (1988): 414427.

Brunner, R. J. "The Evolution of Connecting." Java Developers Journal, 5: no. 10 (2000): 2426. Brunner, R. J. "After the Connection." Java Developers Journal, 5: no. 11 (2000): 4246.

Callahan, T. "So You Want a Stand-Alone Database for Java." Java Developers Journal, 3: no. 12 (1998): 2836.

Codd, E. F. "A Relational Model of Data for Large Shared Data Banks." Communications of the ACM, June 1970.

Codd, E. F. "Further Normalization of the Data Base Relational Model." Courant Computer Science Symposia, Vol. 6, Data Base Systems. Upper Saddle River, NJ: Prentice Hall, 1972.

Codd, E. F. "Fatal Flaws in SQL." Datamation, 34: no. 16 (1988): 4548.

Cooper, J. W. "Making Databases Easier for Your Users." Java Pro, 4: no. 10 (2000): 4754. Date, C. J. An Introduction to Database Systems, 8/e. Reading, MA: Pearson Education, 2003.

Deitel, H. M., P. J. Deitel, and D. R. Choffnes. Operating Systems, Third Edition. Upper Saddle River, NJ: Prentice Hall, 2004.

Duguay, C. "Electronic Mail Merge." Java Pro, Winter 1999/2000, 2232.

Ergul, S. "Transaction Processing with Java." Java Report, January 2001, 3036.

[Page 1229]

Fisher, M. "JDBC Database Access," (a trail in The Java Tutorial), <java.sun.com/docs/books/tutorial/jdbc/index.html>.

Harrison, G., "Browsing the JDBC API." Java Developers Journal, 3: no. 2 (1998): 4452. Jasnowski, M. "Persistence Frameworks." Java Developers Journal, 5: no. 11 (2000): 8286. "JDBC API Documentation." <java.sun.com/j2se/5.0/docs/guide/jdbc/index.html>.

Jordan, D. "An Overview of Sun's Java Data Objects Specification." Java Pro, 4: no. 6 (2000): 102108. Khanna, P. "Managing Object Persistence with JDBC." Java Pro, 4: no. 5 (2000): 2833.

Reese, G. Database Programming with JDBC and Java, Second Edition. Cambridge, MA: O'Reilly, 2001. Spell, B. "Create Enterprise Applications with JDBC 2.0." Java Pro, 4: no. 4 (2000): 4044.

Stonebraker, M. "Operating System Support for Database Management." Communications of the ACM, 24: no. 7 (1981): 412418.

Taylor, A. JDBC Developer's Resource: Database Programming on the Internet. Upper Saddle River, NJ: Prentice Hall, 1999.

Thilmany, C. "Applying Patterns to JDBC Development." Java Developers Journal, 5: no. 6 (2000): 8090.

Venugopal, S. 2000. "Cross-Database Portability with JDBC." Java Developers Journal, 5: no. 1 (2000): 5862.

White, S., M. Fisher, R. Cattell, G. Hamilton and M. Hapner. JDBC API Tutorial and Reference, Second Edition. Boston, MA: Addison Wesley, 1999.

Winston, A. "A Distributed Database Primer." UNIXWorld, April 1988, 5463.

[Page 1229 (continued)]

Summary

A database is an integrated collection of data. A database management system (DBMS) provides mechanisms for storing, organizing, retrieving and modifying data for many users.

Today's most popular database management systems are relational database systems.

SQL is the international standard language used almost universally with relational database systems to perform queries and manipulate data.

Programs connect to, and interact with, relational databases via an interfacesoftware that facilitates communications between a database management system and a program.

Java programmers communicate with databases and manipulate their data using the JDBC API. A

JDBC driver enables Java applications to connect to a database in a particular DBMS and allows programmers to retrieve and manipulate database data.

A relational database stores data in tables. Tables are composed of rows and rows are composed of columns in which values are stored.

A primary key provides a unique value that cannot be duplicated in other rows of the same table.

Each column of a table represents a different attribute.

The primary key can be composed of more than one column.

SQL provides a rich set of language constructs that enable programmers to define complex queries to retrieve data from a database.

Every column in a primary key must have a value, and the value of the primary key must be unique. This is known as the Rule of Entity Integrity.

[Page 1230]

A one-to-many relationship between tables indicates that a row in one table can have many related rows in a separate table.

A foreign key is a column in a table that matches the primary key column in another table.

The foreign key helps maintain the Rule of Referential Integrity: Every foreign key value must

appear as another table's primary key value. Foreign keys enable information from multiple tables to be joined together. There is a one-to-many relationship between a primary key and its corresponding foreign key.

The basic form of a query is

SELECT * FROM tableName

where the asterisk (*) indicates that all columns from tableName should be selected, and tableName specifies the table in the database from which rows will be retrieved.

To retrieve specific columns from a table, replace the asterisk (*) with a comma-separated list of column names.

Programmers process query results by knowing in advance the order of the columns in the

result. Specifying columns explicitly guarantees that they are always returned in the specified order, even if the actual order in the table(s) is different.

The optional WHERE clause in a query specifies the selection criteria for the query. The basic form of a query with selection criteria is

SELECT columnName1, columnName2, ... FROM tableName WHERE criteria

The WHERE clause can contain operators <, >, <=, >=, =, <> and LIKE. Operator LIKE is used for string pattern matching with wildcard characters percent (%) and underscore (_).

A percent character (%) in a pattern indicates that a string matching the pattern can have zero or more characters at the percent character's location in the pattern.

An underscore (_) in the pattern string indicates a single character at that position in the pattern.

The result of a query can be sorted in ascending or descending order using the optional ORDER BY clause. The simplest form of an ORDER BY clause is

SELECT columnName1, columnName2, ... FROM tableName ORDER BY column ASC SELECT columnName1, columnName2, ... FROM tableName ORDER BY column DESC

where ASC specifies ascending order, DESC specifies descending order and column specifies the column on which the sort is based. The default sorting order is ascending, so ASC is optional.

Multiple columns can be used for ordering purposes with an ORDER BY clause of the form

ORDER BY column1 sortingOrder, column2 sortingOrder, ...

The WHERE and ORDER BY clauses can be combined in one query. If used, ORDER BY must be the last clause in the query.

An INNER JOIN merges rows from two tables by matching values in columns that are common to the tables. The basic form for the INNER JOIN operator is:

SELECT columnName1, columnName2,...

FROM table1

INNER JOIN table2

ON table1.columnName = table2.columnName

The ON clause specifies the columns from each table that are compared to determine which rows are joined. If a SQL statement uses columns with the same name from multiple tables, the column names must be fully qualified by prefixing them with their table names and a dot (.).

[Page 1231]

An INSERT statement inserts a new row into a table. The basic form of this statement is

INSERT INTO tableName ( columnName1, columnName2, ..., columnNameN ) VALUES ( value1, value2, ..., valueN )

where tableName is the table in which to insert the row. The tableName is followed by a comma-separated list of column names in parentheses. The list of column names is followed by the SQL keyword VALUES and a comma-separated list of values in parentheses.

SQL uses single quotes (') as the delimiter for strings. To specify a string containing a single quote in SQL, the single quote must be escaped with another single quote.

An UPDATE statement modifies data in a table. The basic form of an UPDATE statement is

UPDATE tableName

SET columnName1 = value1, columnName2 = value2, ..., columnNameN = valueN WHERE criteria

where tableName is the table in which to update data. The tableName is followed by keyword SET and a comma-separated list of column name/value pairs in the format columnName = value. The optional WHERE clause criteria determines which rows to update.

A DELETE statement removes rows from a table. The simplest form for a DELETE statement is

DELETE FROM tableName WHERE criteria

where tableName is the table from which to delete a row (or rows). The optional WHERE criteria determines which rows to delete.

Package java.sql contains classes and interfaces for accessing relational databases in Java.

A program must load a JDBC driver class before the program can connect to a database.

JDBC supports four categories of drivers: JDBC-to-ODBC bridge driver (Type 1), Native-API,

partly Java driver (Type 2), Pure Java client to server driver (Type 3) and Pure Java driver (Type 4).

An object that implements interface Connection manages the Connection between a Java

program and a database. Connection objects enable programs to create SQL statements that access data.

Method getConnection of class DriverManager attempts to connect to a database specified by

its URL argument. The URL helps the program locate the database. The URL includes the protocol for communication, the subprotocol for communication and the name of the database.

Connection method createStatement creates an object of type Statement. The program uses the Statement object to submit SQL statements to the database.

Statement method executeQuery executes a query and returns an object that implements

interface ResultSet containing the query result. ResultSet methods enable a program to manipulate query results.

A ResultSetMetaData object describes a ResultSet's contents. Programs can use metadata programmatically to obtain information about the ResultSet column names and types.

ResultSetMetaData method getColumnCount retrieves the number of ResultSet columns.

ResultSet method next positions the ResultSet cursor to the next row in the ResultSet. The

cursor points to the current row. Method next returns boolean value TRue if it is able to position to the next row; otherwise, the method returns false. This method must be called to begin processing a ResultSet.

When processing ResultSets, it is possible to extract each column of the ResultSet as a specific

Java type. ResultSetMetaData method getColumnType returns a constant integer from class Types (package java.sql) indicating the type of the data for a specific column.

ResultSet get methods typically receive as an argument either a column number (as an int) or a column name (as a String) indicating which column's value to obtain.

[Page 1232]

ResultSet row and column numbers start at 1.

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.

Connection method createStatement has an overloaded version that takes two arguments: the

result type and the result concurrency. The result type specifies whether the ResultSet's cursor is able to scroll in both directions or forward only and whether the ResultSet is sensitive to changes. The result concurrency specifies whether the ResultSet can be updated with ResultSet's update methods.

Some JDBC drivers do not support scrollable or updatable ResultSets.

TableModel method getColumnClass returns a Class object that represents the superclass of all

objects in a particular column. JTable uses this information to set up the default cell renderer and cell editor for that column in a JTable.

ResultSetMetaData method getColumnClassName obtains the fully qualified class name of the specified column.

TableModel method getColumnCount returns the number of columns in the model's underlying

ResultSet.

TableModel method getColumnName returns the name of the column in the model's underlying

ResultSet.

ResultSetMetaData method getColumnName obtains the column name from the ResultSet.

TableModel method getrowCount returns the number of rows in the model's underlying

ResultSet.

TableModel method getValueAt returns the Object at a particular row and column of the model's underlying ResultSet.

ResultSet method absolute positions the ResultSet cursor at a specific row.

AbstractTableModel method fireTableStructureChanged notifies any JTable using a particular

TableModel object as its model that the data in the model has changed.

JDBC enables programs to invoke stored procedures using objects that implement interface

CallableStatement.

CallableStatement can specify input parameters, like PreparedStatement. In addition,

CallableStatement can specify output parameters in which a stored procedure can place return values.

Interface RowSet configures the database connection and executes the query automatically.

There are two types of RowSetsconnected and disconnected.

A connected RowSet connects to the database once and remains connected until the application terminates.

A disconnected RowSet connects to the database, executes a query to retrieve the data from the database and then closes the connection.

JdbcRowSet, a connected RowSet, acts as a wrapper for a ResultSet object, and allows

programmers to scroll and update the rows in the ResultSet. Unlike a ResultSet object, a JdbcRowSet object is scrollable and updatable by default.

CachedRowSet, a disconnected RowSet, caches the data of a ResultSet in memory. Like

JdbcRowSet, a CachedRowSet object is scrollable and updatable. A CachedRowSet object is also serializable, so it can be passed between Java applications through a network, such as the Internet.

[Page 1232 (continued)]

Terminology

% SQL wildcard character

_ SQL wildcard character

absolute method of ResultSet

AbstractTableModel class

addTableModelListener method of TableModel

CachedRowSet interface

[Page 1233]

CallableStatement interface

close method of Connection

close method of Statement

com.mysql.jdbc.Driver

column

connect to a database

connected RowSet

Connection interface

createStatement method of Connection database

DELETE SQL statement deleteRow method of ResultSet

disconnected RowSet

DriverManager class

execute method of JdbcRowSet

execute method of Statement

executeQuery method of Statement

executeUpdate method of Statement