Professional Documents
Culture Documents
C MSA, M SQL, O 9: Onfiguring Ccess Y AND Racle I
C MSA, M SQL, O 9: Onfiguring Ccess Y AND Racle I
Topics in This Chapter Configuring a DSN to connect to Microsoft Access Installing and configuring MySQL Creating databases and users in MySQL Installing and configuring Oracle9i Using the Database Configuration Assistant to create a database in Oracle9i Manually creating a database in Oracle9i Creating users in Oracle9i Testing your database through a JDBC connection Determining the JDBC version of your database driver Setting up the example music table Training courses from the books author: http://courses.coreservlets.com/
Personally developed and taught by Marty Hall Available onsite at your organization (any country) Topics and pace can be customized for your developers Also available periodically at public venues Topics include Java programming, beginning/intermediate servlets and JSP, advanced servlets and JSP, Struts, JSF/MyFaces, Ajax, GWT, Ruby/Rails and more. Ask for custom courses!
18
Training courses from the books author: http://courses.coreservlets.com/
Personally developed and taught by Marty Hall Available onsite at your organization (any country) Topics and pace can be customized for your developers Also available periodically at public venues Topics include Java programming, beginning/intermediate servlets and JSP, advanced servlets and JSP, Struts, JSF/MyFaces, Ajax, GWT, Ruby/Rails and more. Ask for custom courses!
In this chapter, we provide details for configuring three popular databases for use with JDBC: Microsoft Access, MySQL, and Oracle9i. The first database, Microsoft Access, is an excellent database for practice and experimentation because the Java SDK (or JDK) already includes the appropriate JDBC driver and many developers already have Access installed. However, you would be unlikely to use Microsoft Access for serious applications, since it is not designed to handle a large number of concurrent connections. For details on configuring Microsoft Access, see Section 18.1. The second database, MySQL, is a production-quality database and probably the best free option. In Section 18.2 we provide details for installing and configuring MySQL. In addition, we provide information for downloading and using the appropriate MySQL JDBC driver in your Web applications. The third database, Oracle9i, though not free, is an excellent production database. See Section 18.3 for details on installing and configuring Oracle9i. The installation and database creation process is quite lengthy. However, Oracle9i is widely used in industry, so taking the time to gain experience with the product is well worth the effort. After the installation and database creation, we provide information for installing the correct Oracle JDBC driver for use with various versions of the Java SDK. Lastly, we provide programs to test your database and load the example database table used in this book.
555
Chapter 18
3. Select a data source. Locate and select the database file on your computer as the data source for your ODBC connection. Here, you also specify the name of the source to use when connecting to the ODBC driver. 4. Select OK to accept the new DSN. Selecting OK completes the configuration of the ODBC System data source. Afterwards, you can connect to the data source from Java through the JDBC-ODBC bridge.
Figure 181 First window displayed when you are configuring an ODBC data source. Select the System DSN tab and then click the Add button to create a new DSN.
Chapter 18
Figure 182 Second window presented when you are creating a System DSN. Before continuing the configuration, choose the driver for the data source by clicking Finish.
you may need to install the sample database by opening Microsoft Access and selecting the Northwind Sample Database from the opened window. Alternatively, you can download the sample database from http://office.microsoft.com/downloads/2000/ Nwind2K.aspx.
Figure 183 Third window for setting up a System DSN to a Microsoft Access database. Specify the name of the data source (with an optional description) and then select the physical database file to bind to the source name.
Chapter 18
Figure 184 Fourth window presented after you have added a new system data source. Click OK to accept the change.
1. Download and install MySQL. Download MySQL from http://www.mysql.com/downloads/ and install as a service. 2. Create a database. Add a new database to MySQL by entering a simple CREATE DATABASE command. 3. Create a user. To create a user, use GRANT to assign database privileges to the user. 4. Install the JDBC driver. Download the appropriate driver for MySQL, bundled as a JAR file. During development, include the JAR file in your CLASSPATH. For deployment, place the JAR file in the WEB-INF/lib directory of your Web application.
Core Warning
To install MySQL on Windows NT/2000/XP, you must have local administrator rights on the machine.
On Windows NT/2000/XP, to configure MySQL as a service, run the following command in DOS from the C:\mysql\bin directory.
C:\mysql\bin> mysqld-max-nt --install
Create a Database
Before creating a database, you must start the MySQL server. You can start the service from the command line by entering the net start command as shown.
C:\mysql\bin> net start MySql
If the server is already running, you will receive a warning message. Next, to create a new database, start the MySQL monitor as the root user by using the following command.
Prentice Hall and Sun Microsystems Press. Personal use only.
Chapter 18
Then create the database by entering the CREATE DATABASE command as follows.
mysql> CREATE DATABASE database_name;
where database_name is the name of the database you want to create. For the code in this chapter, we created a database named csajsp. To see a listing of the current databases, enter the following command.
mysql> SHOW DATABASES;
If you prefer graphical interfaces over command-line utilities, use MySQL Control Center for managing your server. MySQL Control Center is available at http://www.mysql.com/downloads/mysqlcc.html.
Create a User
You can create a user at the same time you grant privileges to that user. To grant a user access to the database from the local host, use the command
mysql> GRANT ALL PRIVILEGES ON database.* TO user@localhost IDENTIFIED BY 'password';
where database is the name of the database and user is the name of the new user. To grant the user rights to the database from other client machines, use the command
mysql> GRANT ALL PRIVILEGES ON database.* TO user@"%" IDENTIFIED BY 'password';
where @"%" acts as a wildcard for access to the database from any client machine. If you have problems creating new users, check that you started the MySQL monitor as the root user.
URL to use with the MySQL Connector/J driver is jdbc:mysql://host:3306/dbName, where dbName is the name of the database on the MySQL server. Caucho Resin also provides a MySQL driver at http://www.caucho.com/projects/ jdbc-mysql/index.xtp . The driver is bundled in the JAR file named cauchojdbc-mysql-2.1.0.jar with a class name of com.caucho.jdbc.mysql.Driver. The URL to use with the Caucho Resin driver is jdbc:mysql-caucho://host:3306/ dbName, where, again, dbName is the name of the database on the MySQL server. Neither driver is fully JDBC 2.0 compliant since MySQL is not fully ANSI SQL-92 compliant. For development, place the JAR file in your CLASSPATH; for deployment, place the JAR file in the Web applications WEB-INF/lib directory. However, if multiple applications on the server are using MySQL databases, the Web administrator may choose to move the JAR file to a common lib directory on the container. For example, with Tomcat 4.x, JAR files used by multiple applications can be placed in the install_dir/common/lib directory.
Chapter 18
services, database management tools, and utilities; however, the Standard Edition does not support all features available in the Enterprise Edition. Personal Edition. Oracle9i Personal Edition is suitable for a single-user, desktop environment. The Personal Edition is intended for educational purposes, providing a cost-effective, yearly licensing fee. The Personal Edition supports all the features and options available in the Enterprise Edition, with the exception of Oracle Real Application Clusters.
For a more detailed summary of the three Oracle9i Database editions, see
http://otn.oracle.com/products/oracle9i/pdf/9idb_rel2_prod_fam.pdf.
To use Oracle9i, you must install the product, set up a database, and configure users rights. In this section we provide information for downloading and installing Oracle9i Release 2 on Windows XP. For other platforms, you can find platform-specific installation instructions at http://otn.oracle.com/docs/products/oracle9i/. Below, we outline the four steps required to set up an Oracle9i, followed by a detailed description of each step. 1. Download and install Oracle9i. Download Oracle9i Database Release 2 from http://otn.oracle.com/software/products/oracle9i/ and install by using the Oracle Universal Installer. 2. Create a database. Typically, a database is created during the installation of Oracle9i; however, if Oracle9i is already installed on the computer you are using, you can create a new database manually or use the Database Configuration Assistant. 3. Create a user. To access the database from a Web application, you need to create a new user and then grant connection and table rights to the user. 4. Install the JDBC driver. To access an Oracle database from a Web application, download the appropriate JDBC driver from http://otn.oracle.com/software/tech/java/sqlj_jdbc/. During development, include the JAR file in your CLASSPATH. For deployment, place the JAR file in the WEB-INF/lib directory of your Web application.
In the following instructions, we show you how to install Oracle9i Database Release 2 Personal Edition on the Windows XP platform. For installation instructions for other platforms, see the documentation at http://otn.oracle.com/docs/ products/oracle9i/. Oracle9i Database Release 2 for Windows NT/2000/XP is bundled in three ZIP files: 92010NT_Disk1.zip (612,802,971 bytes), 92010NT_Disk2.zip (537,604,934 bytes), and 92010NT_Disk3.zip (254,458,106 bytes). The same install files are used for the Enterprise, Standard, and Personal editions. Follow the instructions on the download page and unzip the three files into corresponding directories named Disk1, Disk2, and Disk3. Alternatively, instead of downloading the software, you can purchase a CD pack at http://oraclestore.oracle.com/. Oracle recommends the following minimum hardware requirements: Pentium 266, 256 Mbytes of RAM, and approximately 3 Gbytes of disk space for an NTFS partition. Exact requirements are available at http://otn.oracle.com/docs/products/ oracle9i/doc_library/release2/A95493-01/html/reqs.htm. Following are the instructions to install Oracle9i Database Personal Edition on the C:\ drive of a Windows XP computer. To perform this installation, you must log in to the machine with local administrator rights.
Core Warning
To install Oracle9i on Windows NT/2000/XP, you must have local administrator rights on the machine.
Chapter 18
2. Specify file locations. On the third screen displayed (Figure 186), you specify the location of the installation program and the directory on which to install Oracle9i. Accept the default values. The Oracle Home, OraHome92, is used in the name for all Oracle services created during the installation process. Click Next to continue.
Figure 186 Third Oracle install window: summarizes the location of source and destination files for the installation process.
3. Select a product to install. On the fourth screen displayed (Figure 187), you select which product to install. Accept the default product, Oracle9i Database, and then click Next.
Figure 187 Fourth Oracle install window: for selecting a product to install.
4. Select the installation type. On the fifth screen displayed (Figure 188), you select the database edition to install. For a single-user environment, we recommend the Personal Edition, which requires 2.53 Gbytes of disk space on Windows XP. For more details on the three editions, see http://otn.oracle.com/ products/oracle9i/pdf/9idb_rel2_prod_fam.pdf. Click Next.
Figure 188 Fifth Oracle install window: for selecting an installation type. For a single user, select the Personal Edition.
Prentice Hall and Sun Microsystems Press. Personal use only.
Chapter 18
5. Select a database configuration. On the sixth screen displayed (Figure 189), you specify the database configuration. We recommend the default selection, General Purpose, because the installation process for this selection automatically creates a starter database. Accept the default database configuration and click Next.
Figure 189 Sixth Oracle install window: for selecting a database configuration.
6. Specify the port for the Oracle MTS Recovery Service. On the seventh screen displayed (Figure 1810), you specify the port for the Oracle MTS Recovery Service, which is automatically installed with Oracle Services for Microsoft Transaction Server. This service helps resolve requests for distributed transaction coordinated by the Microsoft DTC (MS DTC exposes COM objects that allow clients to initiate and participate in coordinated transactions across multiple connections to various data stores). You might not use this capability, so simply accept the default port number of 2030 and click Next.
Figure 1810 Seventh Oracle install window: for specifying a port for the Oracle MTS Recovery Service.
7. Provide a database system identification (SID). On the eighth screen displayed (Figure 1811), you uniquely identify your database. Oracle configuration and utility tools use the SID to identify the database to operate upon. For the JDBC examples presented in this book, we suggest a Global Database Name of csajsp.coreservlets.com. Entering this name will autogenerate a SID of csajsp. Click Next.
Figure 1811 Eighth Oracle install window: for specifying the name of the global database and SID.
Chapter 18
8. Specify a database location. The ninth screen displayed (Figure 1812) defines the physical location of the database. In a production environment, Oracle recommends placing the database on a disk other than the one on which the Oracle9i software is installed. In a development environment, you might have only a single disk available. We used the default suggested location, C:\oracle\oradata. Click Next.
Figure 1812 Ninth Oracle install window: for specifying the physical location of the database.
9. Specify a default character set. On the tenth screen displayed (Figure 1813), you select a character set for your database. Accept the default character set in accordance with the language setting of the operating system.
Figure 1813 Tenth Oracle install window: for selecting the default character set to use for the database.
Prentice Hall and Sun Microsystems Press. Personal use only.
10. Review list of products. The eleventh screen displayed (Figure 1814) summarizes which Oracle products are about to be installed on the computer. After reviewing this list, click the Install button.
Figure 1814 Eleventh Oracle install window: summarizes the products to be installed on the computer.
11. Install Oracle9i. At this point, the Oracle Universal Installer will install Oracle9i. The installer (Figure 1815) indicates the progress of the installation and provides a brief message about each component as it is installed. All installation activity is recorded to a log file located at C:\Program Files\Oracle\Inventory\logs. You can examine the log file for details if the installation fails.
Figure 1815 Twelfth Oracle install window: during the installation of the Oracle components.
Prentice Hall and Sun Microsystems Press. Personal use only.
Chapter 18
12. Install configuration tools. After the core Oracle9i software is installed, you can optionally install configuration tools to manage your database. We recommend that you install the configuration tools. Click Next. Progress of the tool installations is indicated by the Oracle Universal Installer, as shown in Figure 1816.
Figure 1816 Thirteenth Oracle install window: during the installation of configuration tools.
13. Specify passwords. After the configuration tools are installed, the Database Configuration Assistant will prompt you for new SYS and SYSTEM passwords to manage the database (Figure 1817). The default passwords used in many Oracle database products are change_on_install for SYS and manager for SYSTEM. Dont use these commonly known passwords. After specifying new passwords, click OK.
Core Warning
The default passwords for the SYS and SYSTEM administrative accounts are commonly known. For secure administration of your database, specify different passwords.
Figure 1817 Fourteenth Oracle install window: for specifying passwords. Use the Database Configuration Assistant to specify a password for the SYS and SYSTEM administrative accounts.
14. Complete the installation. The last screen displayed (Figure 1818) is the end of the installation process. At this point, Oracle9i Database Release 2 is successfully installed on your computer with a starter database named csajsp. Click Exit to end the Oracle Universal Installer program.
Figure 1818 Fifteenth Oracle install window: completes the installation of Oracle9i.
Chapter 18
Create a Database
Typically, you would create a starter database during installation of Oracle9i. However, if Oracle9i is already installed on the computer you are using, you may want to create a new database. You have two choices for creating a new database. The first choice is to use the Oracle Database Configuration Assistant, which is a graphical configuration tool. The second choice is to manually create the database. To give a better understanding of Oracle9i, we present both approaches for creating a new database. As with the Oracle9i installation, you must have local Windows administrative rights to create a new database.
Core Warning
To create a new Oracle9i database on Windows NT/2000/XP, you must have local administrator rights on the machine.
2. Select an operation. On the second screen displayed (Figure 1820), you select an operation to perform. Select the first option: Create a database. Click Next.
Chapter 18
3. Select a database template. On the third screen displayed (Figure 1821), you select a template for creating the database. Select the template for a new database. Click Next.
4. Provide a database identification. On the fourth screen displayed (Figure 1822), you specify a Global Database Name and SID to identify your new database. Oracle configuration and utility tools use the SID to identify the database to operate upon. For the JDBC examples presented in this book, we suggest a Global Database Name of csajsp.coreservlets.com. Entering this choice will autogenerate a SID of csajsp. Click Next.
Figure 1822 Fourth DBCA window: for specifying the name of the global database and SID.
5. Select the database features to install. On the fifth screen displayed (Figure 1823), you select the features you want to configure for use in your database. To create a simple database for testing, you do not need the optional features; uncheck each of them. If you are prompted with a question to confirm deletion of an associated tablespace, answer Yes. Also, select the Standard database features button and uncheck the four options. Click Next.
Figure 1823 Fifth DBCA window: for selecting the database features to install.
Prentice Hall and Sun Microsystems Press. Personal use only.
Chapter 18
6. Select a database connection option. On the sixth screen displayed (Figure 1824), you select the mode in which you want your database to operate. Select the Dedicated Server Mode option. Click Next.
Figure 1824 Sixth DBCA window: for selecting the operational mode of the database.
7. Specify initialization parameters. On the seventh screen displayed (Figure 1825), you can customize the database. The default parameters are sufficient, so you dont need to customize any of the tab settings. Click Next.
Figure 1825 Seventh DBCA window: for specifying database initialization parameters.
Prentice Hall and Sun Microsystems Press. Personal use only.
8. Specify storage parameters. On the eighth screen displayed (Figure 1826) you specify storage parameters for the database creation. The default storage files and locations are sufficient and require no modification. Click Next.
Figure 1826 Eighth DBCA window: for specifying database storage parameters.
9. Select database creation options. On the ninth screen displayed (Figure 1827), you specify the database creation options. Here, you simply want to create a new database, so check the Create Database option. Click Next.
Figure 1827 Ninth DBCA window: for selecting database creation options.
Prentice Hall and Sun Microsystems Press. Personal use only.
Chapter 18
10. Review the database configuration. At this point, the DBCA presents a summary of all the selected options to create the database, as shown in Figure 1828. After you have reviewed the options, click OK.
Figure 1828 Tenth DBCA window: summarizes the configuration options before the database is created.
11. Monitor the database creation process. The eleventh screen displayed (Figure 1829) indicates activities as the database is created. You can monitor this process if so desired.
Figure 1829 Eleventh DBCA window: during the creation of the database.
12. Specify passwords. After the database is installed, the Database Configuration Assistant will prompt you for SYS and SYSTEM passwords to manage the database (Figure 1830). After specifying new passwords, click OK to complete the database creation process.
Figure 1830 Twelfth DBCA window: for specifying the SYS and SYSTEM administrative passwords.
Chapter 18
4. Create a service for the database. On Windows NT/2000/XP, the database runs as a service. This approach prevents the database from shutting down when the administrator logs off the computer. 5. Declare the ORACLE_SID value. The ORACLE_SID is an environment variable to declare which database to use when running Oracle tools, such as SQL*Plus. 6. Connect to the Oracle service as SYSDBA. To manage and create a database from SQL*Plus, you must connect to the Oracle service as the system database administrator (SYSDBA). 7. Start the database instance. Starting the instance initializes the memory and processes to permit creation and management of a database. If the database instance is not started, the database cannot be created. 8. Create the database. Issue a command in SQL*Plus to create the database, allocating log and temp files. 9. Create a user tablespace. The tablespace stores the tables created by a user of the database. 10. Run scripts to build data dictionary views. Two scripts, catalog.sql and catproc.sql, must be run to set up views and synonyms in the database. The first script, catproc.sql, also configures the database for use with PL/SQL. Next, we provide detailed information about each step.
The bdump directory holds alert and trace files on behalf of background processes. The cdump directory stores a core dump file should the Oracle server fail and be unrecoverable. The udump directory holds trace files used on behalf of a user process. The oradata\csajsp directory contains the physical database.
Core Note
An Oracle instance consists of the memory structure and background processes to manage the database. An initialization parameter file is required for starting an instance.
In practice, most database administrators simply copy and modify an existing parameter file when they need to create a new database. Listing 18.1 presents an example initialization parameter file that creates a database named csajsp on Windows XP. Place this file in the C:\oracle\admin\csajsp\pfile directory. For more information on initialization parameters, see Chapter 1 of the online Oracle9i Database Reference at http://download-west.oracle.com/docs/cd/ B10501_01/server.920/a96536/toc.htm. The minimum parameters that must be specified in an initialization parameter file are background_dump_dest, compatible, control_files, db_block_buffers, db_name, shared_pool_size, and user_dump_dest.
Listing 18.1
# Initialization parameter file for Oracle9i database # on Windows XP. # Database Identification db_domain=coreservlets.com db_name=csajsp # Instance Identification instance_name=csajsp
Chapter 18
Listing 18.1
# Cache and I/O db_block_size=8192 db_cache_size=25165824 db_file_multiblock_read_count=16 # Cursors and Library Cache open_cursors=300 # Diagnostics and Statistics background_dump_dest=C:\oracle\admin\csajsp\bdump core_dump_dest=C:\oracle\admin\csajsp\cdump timed_statistics=TRUE user_dump_dest=C:\oracle\admin\csajsp\udump # File Configuration control_files=("C:\oracle\oradata\csajsp\CONTROL01.CTL", "C:\oracle\oradata\csajsp\CONTROL02.CTL", "C:\oracle\oradata\csajsp\CONTROL03.CTL") # Job Queues job_queue_processes=10 # MTS dispatchers="(PROTOCOL=TCP) (SERVICE=csajspXDB)" # Miscellaneous aq_tm_processes=1 compatible=9.2.0.0.0 # Optimizer hash_join_enabled=TRUE query_rewrite_enabled=FALSE star_transformation_enabled=FALSE # Pools java_pool_size=33554432 large_pool_size=8388608 shared_pool_size=50331648 # Processes and Sessions processes=150 # Redo Log and Recovery fast_start_mttr_target=300
Listing 18.1
# Security and Auditing remote_login_passwordfile=EXCLUSIVE # Sort, Hash Joins, Bitmap Indexes pga_aggregate_target=25165824 sort_area_size=524288 # System Managed Undo and Rollback Segments undo_management=AUTO undo_retention=10800 undo_tablespace=undotbs
creates the password file named PWDcsajsp.ora, with csajspDBA as the SYS user password to administrate the database. The ENTRIES value of 5 defines a total of 5 users (administrators) with SYSDBA privileges in the password file. By convention, for Oracle9i, the password file is placed in the C:\oracle\ora92\DATABASE directory and the name of the password file is PWDdatabase.ora , where database is the name (SID) of the database associated with the password file.
Chapter 18
This command will create a service named OracleServiceCSAJSP, configured to start up manually. When first created, however, the service should start. To check that the service has started, issue the following command.
Prompt> net start OracleServiceCSAJSP
If you want the database service to start when the computer is rebooted, change the service startup type to automatic. To change the startup type on Windows XP, go to the Start menu, then Control Panel, then Performance and Maintenance, then Administrative Tools, Services, then right-click the service to change and select Properties. Next, simply change the Startup type from the available dropdown list.
Note that there should be no spaces around the equal (=) character.
Then, connect to the Oracle service as SYSDBA, using the following command,
SQL> CONNECT SYS/password AS SYSDBA
where password is the SYS password you specified when creating the password file earlier. Note: by your setting of the ORACLE_SID environment variable, SQL*Plus automatically knows the database service in which to connect (OracleServiceCSAJSP, in this case).
The PFILE must refer to the file containing the initialization parameters for the database. Starting the instance in NOMOUNT creates the SGA and starts background processes. However, the database cannot be accessed. Typically, you start a database in NOMOUNT only during creation of the database or during maintenance of the database (e.g., creating control files).
Note that you may need to specify the full path after the @ for SQL*Plus to find the script. Execution of this command (or script) creates the csajsp database in the C:\oracle\oradata\csajsp directory and automatically creates two user accounts, SYS and SYSTEM, to administer the database. SYS is the owner of the database dictionary (information about structure and users of the database), and SYSTEM is the owner of additional tables and views used by Oracle tools. If the database creation fails, examine the alert log file, C:\oracle\admin\csajsp\bdump\alert_csajsp.log, for errors. Correct the problem, delete all the files in the C:\oracle\oradata\csajsp directory, and reissue the command.
Chapter 18
This command creates a tablespace named users with an initial size of 15 Mbytes. The data is physically stored in the file users01.dbf.
The catalog.sql script creates views and synonyms for the data dictionary tables. The catproc.sql script runs all scripts required or used with Oracle PL/SQL. Both of these scripts generate considerable output, which can be ignored; error messages may occur as tables and views are first dropped before being created.
Create a User
To access the database from a Web application, youll need to create a new user with the appropriate rights. From SQL*Plus, enter the following CREATE USER command,
SQL> CREATE USER username IDENTIFIED BY password DEFAULT TABLESPACE users QUOTA UNLIMITED ON users TEMPORARY TABLESPACE temp;
where username is the login name for the new user and password is the password for the new user. The default tablespace is where tables created by the user are placed, and the QUOTA clause grants unlimited use to store information in the users tablespace. If a QUOTA is not specified for the default tablespace, then the user cannot create any tables. A temporary tablespace is also assigned to the user for sorting data if required by the SQL query. Next, you need to grant the new user rights to connect to the database service and to create new tables. Issue the following SQL*Plus command,
SQL> GRANT CREATE SESSION, CREATE TABLE TO username;
where username is the user requiring access to the database. Granting the CREATE TABLE privilege also enables the user to drop tables.
Chapter 18
If multiple applications on the Web server access Oracle databases, the Web administrator may choose to move the JAR file to a common directory on the container. For example, with Tomcat, JAR files used by multiple applications can be placed in the install_dir/common/lib directory. If your Web application server does not recognize ZIP files located in the WEB-INF/ lib directory, you can change the extension of the file to .jar; ZIP and JAR compression algorithms are compatible (JAR files simply include a manifest with metainformation about the archive). However, some developers choose to unzip the file and then create an uncompressed JAR file by using the jar tool with the -0 command option. Both compressed and uncompressed JAR files are supported in a CLASSPATH, but classes from an uncompressed JAR file can load faster. See http://java.sun.com/j2se/1.4.1/ docs/tooldocs/tools.html for platform-specific documentation on the Java archive tool. As a final note, if security is also important in your database transmissions, see
http://download-west.oracle.com/docs/cd/B10501_01/java.920/a96654/ advanc.htm, for ways to encrypt traffic over your JDBC connections. To encrypt the
traffic from the Web server to the client browser, use SSL (for details, see the chapters on Web application security in Volume 2 of this book).
Since TestDatabase is in the coreservlets package, it must reside in a subdirectory called coreservlets . Before compiling the file, set the CLASSPATH to include the directory containing the coreservlets directory. See Section 2.7 (Set Up
Prentice Hall and Sun Microsystems Press. Personal use only.
Your Development Environment) for details. With this setup, simply compile the program by running javac TestDatabase.java from within the coreservlets subdirectory (or by selecting build or compile in your IDE). However, to run TestDatabase, you need to refer to the full package name as shown in the following command,
Prompt> java coreservlets.TestDatabase host dbName username password vendor
where host is the hostname of the database server, dbName is the name of the database you want to test, username and password are those of the user configured to access the database, and vendor is a keyword identifying the vendor driver. This program uses the class DriverUtilities from Chapter 17 (Listing 17.5) to load the vendors driver information and to create a URL to the database. Currently, DriverUtilities supports Microsoft Access, MySQL, and Oracle databases. If you use a different database vendor, you will need to modify DriverUtilities and add the vendor information. See Section 17.3 (Simplifying Database Access with JDBC Utilities) for details. The following shows the output when TestDatabase is run against a MySQL database named csajsp, using the MySQL Connector/J 3.0 driver.
Prompt> java coreservlets.TestDatabase localhost csajsp brown larry MYSQL Testing database connection ... Driver: com.mysql.jdbc.Driver URL: jdbc:mysql://localhost:3306/csajsp Username: brown Password: larry Product name: MySQL Product version: 4.0.12-max-nt Driver Name: MySQL-AB JDBC Driver Driver Version: 3.0.6-stable ( $Date: 2003/02/17 17:01:34 $, $Revision: 1.27.2.1 3 $ ) Creating authors table ... successful Querying authors table ... +-------------+--------------+--------------+ | id | first_name | last_name | +-------------+--------------+--------------+ | 1 | Marty | Hall | | 2 | Larry | Brown | +-------------+--------------+--------------+
Chapter 18
Interestingly, the MySQL Connector/J 3.0 driver used with MySQL 4.0.12 reports a JDBC version of 3.0. However, MySQL is not fully ANSI SQL-92 compliant and the driver cannot be JDBC 3.0 certified. Therefore, you should always check the vendors documentation closely for the JDBC version and always thoroughly test your product before releasing to production.
Core Warning
The JDBC version reported by DatabaseMetaData is unofficial. The driver is not necessarily certified at the level reported. Check the vendor documentation.
public class TestDatabase { private String driver; private String url; private String username; private String password;
Chapter 18
Chapter 18
public void checkJDBCVersion() { System.out.println(); System.out.println("Checking JDBC version ...\n"); Connection connection = getConnection(); if (connection == null) { System.out.println("Check failed."); return; } int majorVersion = 1; int minorVersion = 0; try { Statement statement = connection.createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); String query = "SELECT * FROM authors"; ResultSet resultSet = statement.executeQuery(query); resultSet.last(); // JDBC 2.0 majorVersion = 2; } catch(SQLException sqle) { // Ignore - last() not supported } try { DatabaseMetaData dbMetaData = connection.getMetaData(); majorVersion = dbMetaData.getJDBCMajorVersion(); // JDBC 3.0 minorVersion = dbMetaData.getJDBCMinorVersion(); // JDBC 3.0 } catch(Throwable throwable) { // Ignore - methods not supported } finally { closeConnection(connection); } System.out.println("JDBC Version: " + majorVersion + "." + minorVersion); } // A String of the form "| xxx | xxx | xxx |"
private String makeRow(String[] entries, int[] widths) { String row = "|"; for(int i=0; i<entries.length; i++) { row = row + padString(entries[i], widths[i], " ");
Chapter 18
The music table summarizes the price and availability of concerto recordings for various classical composers. To create the music table in your database, you can run either of the two programs CreateMusicTable.java or create_music_table.sql , as explained in the following subsections.
Chapter 18
CLASSPATH to include the directory containing the coreservlets directory (see Sec-
tion 2.7, Set Up Your Development Environment) and compile the program by running javac CreateMusicTable.java from within the coreservlets subdirectory. However, to create the music table, you must refer to the full package name when executing CreateMusicTable, as shown in the following command,
Prompt> java coreservlets.CreateMusicTable host dbName username password vendor
where host is the hostname of the database server, dbName is the name of the database in which to load the table, username and password are those of the user configured to access the database, and vendor is a keyword identifying the vendor driver (MSACCESS, MYSQL, ORACLE). Thus, if running MySQL on the local host with a database name of csajsp, you might enter the command
Prompt> java coreservlets.CreateMusicTable localhost CSAJSP brown larry MYSQL
where brown is the username and larry is the password to access the database. This program uses two classes from Chapter 17: DriverUtilities in Listing 17.5 and ConnectionInfoBean in Listing 17.9. DriverUtilities loads the driver information and creates a URL to the database. ConnectionInfoBean stores connection information to a database and can create a database connection. Currently, DriverUtilities supports Microsoft Access, MySQL, and Oracle databases. If using a different database vendor, you must modify DriverUtilities and add your specific vendor information. See Section 17.3 (Simplifying Database Access with JDBC Utilities) for details.
Chapter 18
For a MySQL database, you can run the MySQL monitor and execute the SQL script, as shown.
mysql> SOURCE create_music_table.sql
For details on starting MySQL monitor, see Section 18.2. If the script is not located in the same directory in which you started MySQL monitor, you must specify the full path to the script. For an Oracle database, you can run SQL*Plus and execute the SQL script by using either of the following two commands.
SQL> START create_music_table.sql
or
SQL> @create_music_table.sql
For details on starting SQL*Plus, see Section 18.3. Again, if the script is not located in the same directory in which you started SQL*Plus, you must specify the full path to the script.
Chapter 18