Connecting to the Database

   

Connecting to a database using JDBC can be divided into two steps. The first involves loading the JDBC driver and the second step is actually making the connection. Each step is described individually in the following sections.

Loading the Driver

A JDBC driver is loaded using the Class.forName method. The single argument to the method is the name of the driver that you want to load. This may seem a little confusing at first.You need to figure out what the driver class name is from the driver documentation and thencall the forName method. The forName("className") method initializes and loads an instance of the named class and returns the Class object for the class specified by the argument to the forName method.

Caution

When using the forName method on the Class object, you must catch a ClassNotFound exception.


Listing 26.1 shows an example of loading the Oracle8i Lite driver for use with the Oracle8i Lite database.

Listing 26.1 Loading a JDBC Driver
 try   {     Class.forName ( "oracle.lite.poljdbc.POLJDBCDriver"  );   }   catch ( ClassNotFoundException ex )   {     System.out.println ( "Oracle driver not found in class path" );     System.out.println ( ex.getMessage () );   } 

Listing 26.1 is obviously not a complete listing meant to compile, but shows an example of how to load the Oracle8i Lite JDBC driver.

Some of the older documentation that you might find referred developers to create an instance of the driver and register it with the DriverManager. Calling the forName() method will do this for you when you call it with a driver classname. Creating an instance of the driver doesn't really hurt anything. It's just redundant work.

Troubleshooting Tip

If you are having trouble loading the JDBC driver, see "Finding the JDBC Driver Class" in the "Troubleshooting" section at the end on this chapter.


Making the Connection

The second part of getting a connection to a database is actually making the driver establish the connection. As with the first step, this is easy to do. The hardest part of this step is using the correct JDBC URL.

As mentioned in a previous section, the URL specifies everything the driver needs to know to make a connection to the database. You should use one of the three getConnection() methods on the java.sql.DriverManager class to actually perform the connection process. The three different methods are listing here for convenience:

 static Connection getConnection(String url); static Connection getConnection(String url, Properties info); static Connection getConnection(String url, String user, String password); 

Notice that the three methods return a single instance of a Connection object. A Connection is really a Java interface from the java.sql package that represents a session with a database.

The only differences between the three methods are the additional parameters for specifying either a Properties instance or two strings for user and password. Depending on the specific URL format for your JDBC driver, you will need to use a certain getConnection() method. If for example, the URL format for your driver has the user and password specified in the URL itself, you probably can get away with using the first method format, otherwise you might have to use the second or third. The second format that has an instance of the Properties class as the second parameter, can be used to set key/value pairs that are then used by the driver to establish a connection. An example of a key/value pair might be username="SCOTT" and password="tiger". Some of the older driver URLs did not support having the username and password values in the URL itself. You needed to set them in the Properties instance and pass the Properties instance along with the URL in the getConnection() method.

Take a look at a complete example that establishes a connection to Oracle. Listing 26.2 shows a class called DatabaseManager, which is responsible for creating and returning instances of the Connection interface on which other Java classes can make SQL calls. This class will be reused throughout the examples in this chapter, so it's a good idea to become familiar with its operation. The DatabaseManager has all the information it needs to connect to the database, including the complete JDBC URL. Later, you'll learn the good points and the bad points about a design like this.

Note

The example POLITE database that comes with the Oracle Lite installation is used in the following example.


Listing 26.2 Source Code for DatabaseManager.java
 import java.sql.*; import java.util.*; public class DatabaseManager {   // These properties could come from a system configuration file   static private String urlHeader = "jdbc:polite:";   static private String databaseName = "POLITE";   static private String user = "SYSTEM";   static private String password = "";   static private String driverName = "oracle.lite.poljdbc.POLJDBCDriver";   public static Connection getConnection()   {     // Define the local Connection instance that gets returned     Connection conn = null;     try     {       // Load the JDBC driver       Class.forName( driverName );       // Get an instance of the Connection. Really the Connection is an       // interface that some class implements.       // Concat the three parts together to build the full URL String databaseURL = urlHeader + databaseName;       conn = DriverManager.getConnection( databaseURL, user, password );     }     catch( ClassNotFoundException ex )     {       // The JDBC driver class could not be found       ex.printStackTrace();       System.exit( -1 );     }     catch( SQLException ex )     {       // A sql exception occurred, for now just print out the stack trace       ex.printStackTrace();     }     return conn;   } } 

Listing 26.3 shows the class that is used to test the DatabaseManager class from Listing 26.2.

Listing 26.3 Source Code for DatabaseConnectTest.java
 import java.sql.*; public class DatabaseConnectTest {   public static void main(String[] args)   {     // Get an instance of a Connection from the DatabaseManager     // who is performing Creator pattern here by creating instances of     // a class that implements the Connection interface.     Connection conn = DatabaseManager.getConnection();     if ( conn != null )     {       System.out.println( "Connection attempt was successful!" );       try       {         conn.close();       }       catch( SQLException ex )       {         ex.printStackTrace();         System.out.println( "Problem closing the connection" );       }     }   } } 

There's not much output for this example. It should look like the output in Listing 26.4.

Listing 26.4 DatabaseConnectTest Output
 C:\jdk1.3se_book\classes>java DatabaseConnectTest Connection attempt was successful! C:\jdk1.3se_book\classes> 

Let's take a closer look at the DatabaseManager class from Listing 26.2 and see exactly what it's doing. The first thing to notice about this class is it defines some private static variables that contain information about the database that it will connect to. As this is a very easy and simple way to handle the connection information, it's not very flexible. If one or more of the connection values changes, then the software would need to be recompiled. It's probably not a great solution. A better solution would be to read it from a java.util.Properties file. It will do for now.

The next interesting thing to notice in the case takes place just inside the try block. This is where the database driver class is loaded and a connection is established to the database. Notice that you must catch a ClassNotFoundException, just in case the driver is not in the system CLASSPATH.

Finally, if a connection was established it is returned to the back to the caller. Otherwise, null will be returned. The DatabaseConnectTest class in Listing 26.3 checks to see if the connection that was returned is null. It prints out some information either way.

Another thought is that because the time it takes to actually get the connection to the database is considerable, you might want to create a pool of database connections when the system starts and then use the connections when a client asks for them. When the client is finished, it hands it back to the DatabaseManager, which would recycle it by putting it back into the pool of connections. This concept and several others are discussed in the next chapter in the sections about connection pooling.

   


Special Edition Using Java 2 Standard Edition
Special Edition Using Java 2, Standard Edition (Special Edition Using...)
ISBN: 0789724685
EAN: 2147483647
Year: 1999
Pages: 353

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net