Sun Java Solaris Communities My SDN Account Join SDN
 
Java Technology Fundamentals Newsletter Index

Java Technology Fundamentals Newsletter

 

New-to-Java Programming Center
Technology Fundamentals

Welcome to the Java Developer Connection Java Technology Fundamentals Newsletter.

This monthly newsletter provides a way for you to learn the basics of the Java programming language, discover new resources, and keep up-to-date on the latest additions to the JDC's New to Java Programming Center.

CONTENTS

1. Java Programming Language Basics

Connecting to a Database Using JDBC Technology

2. Making Sense of the Java Class Libraries

Interfaces Connection and DatabaseMetaData, and the DriverManager Class

3. Program Challenge

MetaTest Application

4. Java Bits

JDBC and JDO

5. New to the Programming Center

Building an Application, Part 4

6. For More Information

Read articles, Tech Tips, trails, and tutorials that provide more information on the topics discussed here.

Java Programming Language Basics

Connecting to a Database Using JDBC Technology

JDBC is the library from the Java 2 Standard Edition (J2SE), used to communicate with SQL-based databases. To follow this article, you'll need access to a database. If you don't have one, MySQL is free, open source, and it works in many different operating environments. See For More Information below for links to download MySQL.

fig 1

In addition to having a working database, you need a JDBC driver. While JDBC is designed to work with just about all databases, you need a driver that works with your specific database. Drivers come in many varieties, including some that work with multiple databases, and can be located through JDBC Technology - Drivers. See For More Information below for link.

Essentially, the driver maps JDBC commands to the database you are using. If you happen to be using MySQL, you can get a MySQL driver from Sourceforge.net or MySQL.org.

With a database server running and a JDBC driver available, you can work with the JDBC libraries. As with any classes, make the JDBC driver classes available to the compiler and runtime environment. Configure the CLASSPATH environment variable or copy the appropriate JAR file with the classes to the $JAVA_HOME/jre/lib/ext directory, located under the base installation directory of your Java 2 Platform (J2SE) download.

Once you've set up the environment for your database and driver, you can start coding. There are two tasks involved in getting started with JDBC:

Step 1: Load the necessary JDBC driver. Just making the classes available to the runtime environment isn't sufficient.

Step 2: Connect to the database. Connecting involves identifying the specific data source. Based on that data source, the appropriate driver is used.

fig 2

As described below, there is more than one way to perform the tasks outlined in these two steps.

Step 1: Loading the JDBC Driver

In their simplest sense, JDBC drivers are just classes. They must implement the java.sql.Driver interface, but developers seldom need to use the interface directly. The only requirement for a driver implementation is that the class must register itself with the java.sql.DriverManager when the class is loaded. This requirement is the responsiblity of the driver vendor, not you as the user of the driver. All you need to do is load the class, which can be done in three different ways.

The first possible way to load a JDBC driver:

Create an actual instance of the class. After identifying your database and finding the specific driver you want to use, you can hard code a call to the constructor.

For instance, with mysql-2.0.13-bin.jar in your path to access MySQL, you would need to create an instance of the org.gjt.mm.mysql.Driver class:

Driver d = new org.gjt.mm.mysql.Driver();

This technique works fine to load the driver, but it does have drawbacks. While JDBC is database-agnostic, you are requiring the user of your application to use MySQL. If the user happens to be an Oracle or Sybase user, well, too bad. They must still get MySQL to run your program.

Another problem is that by explicitly creating an instance of the driver, you are actually causing two instances to be created. As previously stated, the driver is required to register itself with the DriverManager when the class is loaded. So, when the class is loaded, the class creates an instance of itself and registers itself with the DriverManager. By calling the constructor directly, you are creating a second instance.

The second possible way to load a JDBC driver:

To avoid creating two instances of the driver, pass the class name as a string to the forName method of Class. That class name is fully qualified, like org.gjt.mm.mysql.Driver for the MySQL driver, and as a quoted string, as shown here:

Class.forName("org.gjt.mm.mysql.Driver");

In both cases above, you are hard coding the name of the database driver, but the second way is preferable. Since the driver is loaded dynamically at runtime, the classes for the driver do not have to be made available at compile time, and you don't have to hard code a string there. What you can do is get the driver name from the command line or elsewhere and pass it through. That way, you can test with MySQL on your desktop, and your customer can use Oracle on their server, without source code changes or recompilations.

String driver = args[0];
Class.forName(driver);

The third way to load a JDBC driver:

The first two loading techniques require you to pass the driver names in from somewhere. There's a third way to load the driver that doesn't require any source code. Specify the driver, or set of drivers, by setting the jdbc.drivers system property, as shown here:

java -Djdbc.drivers=org.gjt.mm.mysql.Driver ProgName

Now the driver is automatically available to the DriverManager when you need it. If multiple drivers are to be made available, the list is colon separated.

Step 2: Connecting to the Database

Data sources are identified by a URI which begins with "jdbc:". What follows jdbc: depends on your JDBC driver. Each driver provides a unique string to map to the driver, and some mechanism to locate the server to which the driver is to speak.

In the case of the MySQL driver, the string is quite aptly "mysql" and the location is specified by another URI. The format of the entire string looks something like the following:

jdbc:mysql://[hostname][:port]/[dbname][?param1=value1][¶m2=value2].....

More specifically, if the host you want to connect to is your own machine, the database name is test, and you don't want to provide a username and password, the final string would look as follows:

jdbc:mysql://localhost/test

Once you have the appropriate URI necessary to identify the driver and let the driver connect to the data source, it's time to make the actual connection to the source. The DriverManager provides a getConnection method for just such a lookup. It returns the Connection object from the first driver that supports the specified protocol (mysql in this case). If no registered driver supports the protocol, an exception is thrown at runtime.

String uri = "jdbc:mysql://localhost/test";
Connection con =
   DriverManager.getConnection(uri, username, password);

The name of the subprotocol, mysql here, is specified in the documentation for your JDBC driver.

Once you've made a connection to your data source, you're ready to access it. There is, however, a second way to identify and connect to a data source: data sources can be acquired through the Java Naming and Directory Interface (JNDI) naming service.

When using JNDI to make a connection, instead of using Driver and DriverManager, you use DriverSource and Context. In the particular case of MySQL, the javax.sql.DriverSource implementation is the org.gjt.mm.mysql.jdbc2.optional.MysqlDataSource class, but that is typically registered outside the scope of your application. All your application needs to do is look up the data source based on the name bound to the context.

Context ctx = new InitialContext();
ctx.addToEnvironment(Context.INITIAL_CONTEXT_FACTORY,
   "com.sun.jndi.fscontext.RefFSContextFactory");
DataSource ds = (DataSource)ctx.lookup("/tmp/jdbc/test");
Connection con = ds.getConnection(username, password);

Once you have the connection, you access the database in the same way as the DriverManager lookup. The DataSource lookup is typically done in the context of a J2EE application.

You'll know when you have a JNDI environment available; it usually isn't set up to only look up a JDBC source.

To try out both ways of connecting to the database, MySQL comes with a test suite. Look in the test suite package for the statements and JNDIDataSource test cases. If you use a different database, you can either check for its own test cases or make minor adjustments to these to use the specific driver and data source of the other database.

Test your knowledge about connecting to a database with JDBC with this online quiz.

Making Sense of the Java Class Libraries

Interfaces Connection and DatabaseMetaData, and the DriverManager Class

JDBC provides the API for accessing and processing data stored in a data source, such as a relational database using the Java programming language. The API includes the java.sql package, referred to as the JDBC core API, and the javax.sql package, referred to as the JDBC Optional Package API, and is included in the J2SE, version 1.4 download.

The interfaces and class discussed here are found in the java.sql package.

fig 3

The Connection interface represents a session with the database connection provided by the driver. It also provides methods for creating statements and managing connections and their properties. A Connection object's database can provide information describing its tables, its supported SQL grammar, its stored procedures, the capabilities of this connection, and so on. This information is obtained with the getMetaData method:

public DatabaseMetaData getMetaData()
                     throws SQLException 

The DriverManager class is a utility class that manages JDBC drivers. It holds a list of registered JDBC drivers for the system, and makes a connection with a driver. You use this class primarily to get a Connection object reference through the getConnection method:

  • getConnection(String url)
    Attempts to establish a connection to the given database URL.

  • getConnection(String url, Properties info)
    Attempts to establish a connection to the given database URL. Parameters: url - a database url of the form jdbc:subprotocol:subname info - a list of arbitrary String tag/value pairs as connection arguments. Normally at least a "user" and "password" property should be included.

  • getConnection(String url, String user, String password) Attempts to establish a connection to the given database URL. Parameters: url - a database url of the form jdbc:subprotocol:subname user - the database user on whose behalf the connection is being made password - the user's password

DatabaseMetaData interface provides information about the database. Some methods in this interface take string patterns. A method that gets information about a feature that the driver does not support throws an SQLException.

A few methods:

  • getDriverName
    Retrieves the name of this JDBC driver.
  • getDriverVersion
    Retrieves the version number of this JDBC driver as a string.
  • getDatabaseProductVersion
    Retrieves the version number of this database product.

Program Challenge

  • Create a program that connects to your database
  • Display information about the database and driver used to make the connection.

Methods to access database information are available through the DatabaseMetaData associated with the connection.

See a possible solution to Challenge.

Java Bits

JDO (Java Data Objects) is an API for transparent database access. A programmer can write code using the Java programming language that transparently accesses the underlying data store, without using database-specific code.

The JDO and JDBC APIs are complementary approaches. These technologies have unique strengths and can be used by programmers with different skill sets and development objectives.

JDBC API provides greater flexibility by giving programmers direct control over database access and cache management. The JDBC API is a more mature technology, and is broadly accepted as a complete API.

JDO provides programmer convenience and compile-time type checking. In addition, JDO hides SQL from the programmer so that learning SQL is not necessary.

The JDO API is being created under the Java Community Process.

New to Java Programming Center

Learn how to create scroll bars, pop-up option boxes, and how to read from and write to files.

Building an Application, Part 4

For More Information

Download and Install MySQL

JDBC Data Access API

Establishing a Connection

JDBC 2.0 Fundamentals

DriverManager

Connection

Interface DatabaseMetaData

Java Naming and Directory Interface (JNDI)

JDO API

Java Community Process

New to Java Programming Center

Building an Application Introduction

Program Challenge Solution

See one possible solution to the June Program Challenge.

Downloading the Java 2 Platform

For most Java development, you need the class libraries, compiler, tools, and runtime environment provided with the J2SE development kit.

IMPORTANT: Please read our Terms of Use and Privacy policies:

Copyright 2002 Sun Microsystems, Inc. All rights reserved.
901 San Antonio Road, Palo Alto, California 94303 USA

FEEDBACK

Tell us what you think of this supplement.

Duke

 Very worth reading  Worth reading  Not worth reading

If you have other comments or ideas for future technical content, please type them here:

Have a question about programming? Use Java Online Support.

- Note -

Sun respects your online time and privacy. The Java Developer Connection mailing lists are used for internal Sun Microsystems purposes only. You have received this email because you elected to subscribe.

- Subscribe/Unsubscribe -

To subscribe, go to the subscriptions page, choose the newsletters you want to subscribe to and click Update

To unsubscribe, go to the subscriptions page, uncheck the appropriate check box, and click Update

This document is protected by copyright.

Java Technology Fundamentals
June 2002

Sun, Sun Microsystems, Java, J2SE, JDBC are trademarks or registered trademarks of Sun Microsystems, Inc. in the United States and other countries.