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

AhmadLang / Java, How To Program, 2004

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

3

Tem

Nieto

4

Sean

Santry

 

 

 

[Page 1206]

25.5. Instructions to install MySQL and MySQL Connector/J

The CD that accompanies this book includes MySQL 4.0.20an open-source database management system. MySQL executes on many platforms, including Windows, Solaris, Linux, and Macintosh. Complete information about MySQL is available from

www.mysql.com/products/mysql/

To install MySQL:

1. Insert the CD into the CD drive (the D: drive on our system), and change directories to

D:\software\MySQL\mysql-4.0.20c-win.

2. Double click SETUP.EXE to start the MySQL installer. Follow the instructions to install MySQL in the C:\mysql directory, which is the default directory.

Instructions for installing MySQL can also be found in Chapter 2 of the MySQL Manual at dev.mysql.com/doc/mysql/en/index.html.

To use MySQL with JDBC, you also need to install MySQL Connector/Ja JDBC driver that allows programs to access MySQL databases via JDBC. MySQL Connector/J is on the CD that accompanies this book and can also be downloaded from

www.mysql.com/products/connector/j/

At the time of this writing, the current stable release of MySQL Connector/J is 3.0.14. To install MySQL Connector/J:

1. Copy mysql-connector-java-3.0.14-production.zip to your hard disk.

2. Open mysql-connector-java-3.0.14-production.zip with a file extractor, such as WinZip, which can be downloaded from www.winzip.com. Extract its content to the C:\ drive. This will create a directory named mysql-connector-java-3.0.14-production. The documentation for MySQL Connector/J is in connector-j-en.pdf in the docs subdirectory of mysql-connector- java-3.0.14-production, or you can view it online at dev.mysql.com/doc/connector/j/en/index.html.

[Page 1206 (continued)]

25.6. Instructions on Setting MySQL User Account

For the examples in the book to execute correctly, you need to set up a user account that allows users to create, delete and modify a database. After MySQL is installed, follow the steps below to set up a user account (these steps assume MySQL is installed in its default installation directory):

1. Open a Command Prompt and start the database server by executing the C:\mysql\bin\mysqld script.

2. Open another Command Prompt and change to the C:\mysql\bin directory. To start the MySQL monitor so you can set up a user account, execute the command

C:\mysql\bin>mysql -h localhost -u root

[Page 1207]

3. For our examples, we set up a user account on the local computer (localhost) with the username set "jhtp6" and the password "jhtp6". To do this, execute the following commands in the Command Prompt created in Step 2:

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 1207 (continued)]

25.7. Creating Database books in MySQL

For each MySQL database we discuss in this book, we provide a SQL script that will set up the database and its tables. These scripts can be executed with a command-line tool called mysql that is part of the MySQL installation. In the examples directory for this chapter on the CD that accompanies this book, you will find the SQL script books.sql.

To create the books database:

1.Open a Command Prompt and change to the C:\mysql\bin directory. [Note: If you installed MySQL on a directory other than C:\mysql, replace C:\mysql with your MySQL installation directory.]

2.Start the database server by executing the command

C:\mysql\bin>mysqld

3.Copy the SQL script books.sql to the C:\mysql\bin directory. [Note: If you installed MySQL on a directory other than C:\mysql, replace C:\mysql with your MySQL installation directory.]

4.Open a new Command Prompt and change to the C:\mysql\bin directory. [Note: If you installed MySQL on a directory other than C:\mysql, replace C:\mysql with your MySQL installation directory.]

5.Create the books database by executing the command

C:\mysql\bin>mysql -h localhost -u jhtp6 -p < books.sql

When the above command is executed, you are prompted for entering the password, which is jhtp6. After completing this task, a new directory named books will be created in the C:\mysql\data directory. This new directory contains the books database. You are now ready to proceed to the first JDBC example.

[Page 1207 (continued)]

25.8. Manipulating Databases with JDBC

In this section, we present two examples. The first example introduces how to connect to a database and query the database. The second example demonstrates how to display the result of the query in a JTable.

[Page 1208]

25.8.1. Connecting to and Querying a Database

The example of Fig. 25.25 performs a simple query on the books database that retrieves the entire authors table and displays the data. The program illustrates connecting to the database, querying the database and processing the result. The following discussion presents the key JDBC aspects of the program. [Note: Section 25.5 demonstrates how to start the MySQL server, how to prepare the MySQL database and how to create the books database. The steps in Section 25.5 must be performed before executing the program of Fig. 25.25.]

Figure 25.25. Displaying the authors table from the books database.

(This item is displayed on pages 1208 - 1209 in the print version)

1 // Fig. 25.25: DisplayAuthors.java

2 // Displaying the contents of the authors table.

3import java.sql.Connection;

4import java.sql.Statement;

5import java.sql.DriverManager;

6import java.sql.ResultSet;

7import java.sql.ResultSetMetaData;

8import java.sql.SQLException;

9

10public class DisplayAuthors

11{

12// JDBC driver name and database URL

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

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

16// launch the application

17public static void main( String args[] )

18{

19Connection connection = null; // manages connection

20Statement statement = null; // query statement

21

22// connect to database books and query database

23try

24{

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

27// establish connection to database

28connection =

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

31// create Statement for querying database

32statement = connection.createStatement();

34// query database

35ResultSet resultSet = statement.executeQuery(

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

38// process query results

39ResultSetMetaData metaData = resultSet.getMetaData();

40int numberOfColumns = metaData.getColumnCount();

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

43

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

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

45System.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 ) );

51System.out.println();

52} // end while

53} // end try

54catch ( SQLException sqlException )

55{

56sqlException.printStackTrace();

57System.exit( 1 );

58} // end catch

59catch ( ClassNotFoundException classNotFound )

60{

61classNotFound.printStackTrace();

62System.exit( 1 );

63} // end catch

64finally // ensure statement and connection are closed properly

65{

66try

67{

68statement.close();

69connection.close();

70} // end try

71catch ( Exception exception )

72{

73exception.printStackTrace();

74System.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

 

 

 

Lines 38 import the JDBC interfaces and classes from package java.sql used in this program. Line 13 declares a String constant that contains theMySQL JDBC driver's class name. The program will use this value to load the proper driver into memory. Line 14 declares a string constant for the database URL. This identifies the name of the database to connect to, as well as information about the protocol used by the JDBC driver (discussed shortly). Method main (lines 1776) connects to the books database, queries the database, displays the result of the query and closes the database connection.

[Page 1210]

The program must load the database driver before connecting to the database. Line 25 uses static method

forName of class Class to load the class for the database driver. This line throws a checked exception of type java.lang.ClassNotFoundException if the class loader cannot locate the driver class. To avoid this exception, you need to include the mysql-connector-java-3.0.14-production-bin.jar (in the C:\mysql- connector-java-3.0.14-production directory) in your program's classpath when you execute the program, as in:

[View full width]

java -classpath c:\mysql-connector-java-3.0.14-production\mysql-connector-java-3.0 .14-production-bin.jar;. DisplayAuthors

In the above command, notice the period (.) before DisplayAuthors. If this period is missing, the JVM will not find the DisplayAuthors class file. You may also copy the mysql-connector-java-3.0.14-production-bin.jar file to the JRE's lib\ext directory, e.g., C:\Program Files\Java\jdk1.5.0\jre\lib\ext. After doing so, you could run the application simply using the command java DisplayAuthors.

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). A description of each driver type is shown in Fig. 25.26. The MySQL driver com.mysql.jdbc.Driver is a Type-4 driver.

Figure 25.26. JDBC driver types.

Type Description

1The 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.

2Native-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 databasespecific calls. Type 2 drivers were introduced for reasons similar to the Type 1 ODBC bridge driver.

3Pure 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.

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

[Page 1211]

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.

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.

Lines 2829 of Fig. 25.25 creates a Connection object (package java.sql) referenced by connection. An object that implements interface Connection manages the connection between the Java program and the database. Connection objects enable programs to create SQL statements that access databases. The program initializes Connection with the result of a call to static method getConnection of class DriverManager (package java.sql), which attempts to connect to the database specified by its URL. Method getConnection takes three argumentsa String that specifies the database URL, a String that specifies the username and a String that specifies the password. The username and password are set in Section 25.6. If you used different

username and password, you need to replace the username (second argument) and password (third argument) passed to method getConnection in line 29. The URL locates the database (possibly on a network or in the local file system of the computer). The URL jdbc:mysql://localhost/books specifies the protocol for communication (jdbc), the subprotocol for communication (mysql) and the location of the database (//localhost/books, where localhost is the name of the MySQL server host and books is the database name). The subprotocol mysql indicates that the program uses a MySQL-specific subprotocol to connect to the MySQL database. If the DriverManager cannot connect to the database, method getConnection tHRows a SQLException (package java.sql). Figure 25.27 lists the JDBC driver names and database URL formats of several popular RDBMSs.

Figure 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/

 

 

databaseName

Sybase

com.sybase.jdbc.SybDriver

jdbc:sybase:Tds: hostname:

 

 

portnumber/ databaseName

 

 

 

[Page 1212]

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.

Line 32 invokes Connection method createStatement to obtain an object that implements interface Statement (package java.sql). The program uses the Statement object to submit SQL to the database.

Lines 3536 use the Statement object's executeQuery method to submit a query that selects all the author information from table authors. This method returns an object that implements interface ResultSet and contains the result of the query. The ResultSet methods enable the program to manipulate the query result.

Lines 3952 process the ResultSet. Line 39 obtains the metadata for the ResultSet as a

ResultSetMetaData (package java.sql) object. The metadata describes the ResultSet's contents. Programs can use metadata programmatically to obtain information about the ResultSet's column names and types. Line 40 uses ResultSetMetaData method getColumnCount to retrieve the number of columns in the ResultSet. Lines 4243 display the column names.

Software Engineering Observation 25.7

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

Lines 4752 display the data in each ResultSet row. Before processing the ResultSet, the program positions the ResultSet cursor to the first row in the ResultSet with method next (line 47). 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.

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.

If there are rows in the ResultSet, line 50 extracts the contents of one column in the current row. When processing a ResultSet, it is possible to extract each column of the ResultSet as a specific Java type. In fact, ResultSetMetaData method getColumnType returns a constant integer from class Types (package java.sql) indicating the type of a specified column. Programs can use these values in a switch statement to invoke ResultSet methods that return the column values as appropriate Java types. If the type of a column is Types.INT, ResultSet method getInt returns the column value as an int. 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. Visit

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

for detailed mappings of SQL data types to Java types and to determine the appropriate ResultSet method to call for each SQL data type.

[Page 1213]

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.

For simplicity, this example treats each value as an Object. The program retrieves each column value with ResultSet method getObject (line 50) and prints the String representation of the Object. Note that, unlike array indices, which start at 0, ResultSet column numbers start at 1. The finally block (lines 6476) closes the Statement (line 68) and the database Connection (line 69).

Common Programming Error 25.9

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

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.

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.

25.8.2. Querying the books Database

The next example (Fig. 25.28 and Fig. 25.31) allows the user to enter any query into the program. The example displays the result of a query in a JTable, using a TableModel object to provide the ResultSet data to the JTable. Class ResultSetTableModel (Fig. 25.28) performs the connection to the database and maintains the ResultSet. Class DisplayQueryResults (Fig. 25.31) creates the GUI and specifies an instance of class

ResultSetTableModel to provide data for the JTable.

Figure 25.28. ResultSetTableModel enables a JTable to display the contents of

a ResultSet.

(This item is displayed on pages 1214 - 1217 in the print version)

1// Fig. 25.28: ResultSetTableModel.java

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

3import java.sql.Connection;

4import java.sql.Statement;

5import java.sql.DriverManager;

6import java.sql.ResultSet;

7import java.sql.ResultSetMetaData;

8import java.sql.SQLException;

9import javax.swing.table.AbstractTableModel;

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

17public class ResultSetTableModel extends AbstractTableModel

18{

19private Connection connection;

20private Statement statement;

21private ResultSet resultSet;

22private ResultSetMetaData metaData;

23private int numberOfRows;

24

25// keep track of database connection status

26private boolean connectedToDatabase = false;

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

29// determines number of rows

30public ResultSetTableModel( String driver, String url,

31String username, String password, String query )

32throws SQLException, ClassNotFoundException

33{

34// load database driver class

35Class.forName( driver );

36

37// connect to database

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

40// create Statement to query database

41statement = connection.createStatement(

42ResultSet.TYPE_SCROLL_INSENSITIVE,

43ResultSet.CONCUR_READ_ONLY );

44

45// update database connection status

46connectedToDatabase = true;

47