Using the PostgreSQL Driver

This section describes the process for using the built PostgreSQL JDBC driver. First add, the path to your postgresql.jar file into your CLASSPATH setting. This can be done either by setting your CLASSPATH environment variable, or by passing the path as an argument on the command line to your Java executable each time a Java application is executed. For more information, see your JVM vendor's instructions for setting your classpath.

Next, when coding a Java application, you need to ensure that within your code the Driver gets registered. When the Driver class passes through the Java class loader, it registers itself with the DriverManager class so that JDBC will know what Driver to use when connecting to a specific type of database. For instance, when you connect to a PostgreSQL database, you would obviously use the PostgreSQL driver class.

To make sure that the Driver class passes through the class loader, you can do a lookup by class name, as shown in the Java code snippet in Example 12-1.

Example 12-1. Class Name Lookup

try {
  Class.forName("org.postgresql.Driver");
} catch (ClassNotFoundException cnfe) {
  System.err.println("Couldn't find driver class:");
  cnfe.printStackTrace();
}

Class.forName is a method that finds a class by name. In this case, you look for the Driver. This causes the class loader to search through the CLASSPATH and find a class by that name. If it finds it, the class loader will then read in the binary description of the class. If it does not find it, it will throw a ClassNotFoundException, in which case you can print out an error message to that effect. If you reach this state, you either haven't built the driver correctly, or the built .jar file is not in your classpath.

Once you have registered this class, you need to request a connection to a PostgreSQL database. To do this, you use a class called DriverManager. The DriverManager class is responsible for handling JDBC URLs, finding an appropriate driver, and then using that driver to provide a connection to the database.

JDBC URLs are of the following format, in three colon-delimited parts:

jdbc:[drivertype]:[database]

The first part, jdbc, is a constant. It represents that you are connecting to a JDBC data source. The second part, [drivertype], represents the kind of database you want to connect to. Use postgresql to connect to a PostgreSQL database. The third part is passed off to the driver, which finds the actual database. It takes on one of the following formats:

databasename
//hostname/databasename
//hostname:portnumber/databasename

In the first case, the PostgreSQL database is running on the local machine, on the default port number. The databasename is the literal name of the database you wish to connect to. The second case is used for when you want to specify a hostname and a database. This also uses the default port number. The third case allows you to specify a port number as well. Even if you use the first type of URL, the JDBC connection will always be made via TCP/IP.

For the purposes of the examples from now on, this chapter will use the URL: jdbc:postgresql://example/bookstore, meaning you are connecting to host example and database bookstore. With that in mind, try to make a connection, using all you have learned so far. Example 12-2 shows a simple Java program that opens a JDBC connection to the bookstore database. If you run the example yourself, be sure to replace the username and password with values that will work on your system.

Example 12-2. A Simple JDBC Connection

import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.SQLException;

public class Example1 {
  public static void main(String[] argv) {
  System.out.println("Checking if Driver is registered with DriverManager.");
  
  try {
    Class.forName("org.postgresql.Driver");
  } catch (ClassNotFoundException cnfe) {
    System.out.println("Couldn't find the driver!");
    System.out.println("Let's print a stack trace, and exit.");
    cnfe.printStackTrace();
    System.exit(1);
  }
  
  System.out.println("Registered the driver ok, so let's make a connection.");
  
  Connection c = null;
  
  try {
    // The second and third arguments are the username and password, 
    // respectively. They should be whatever is necessary to connect
    // to the database.
    c = DriverManager.getConnection("jdbc:postgresql://example/bookstore", 
                                    "username", "password");
  } catch (SQLException se) {
    System.out.println("Couldn't connect: print out a stack trace and exit.");
    se.printStackTrace();
    System.exit(1);
  }
  
  if (c != null)
    System.out.println("Hooray! We connected to the database!");
  else
    System.out.println("We should never get here.");
  }
}

At this point you should be able to use this Connection object to do anything you want with the PostgreSQL database.

Notice also the first three lines of Example 12-2. These three import statements make available the required classes to register with the DriverManager object, to create a Connection object, and to use SQLException objects. In general, to make available a JDBC class, the syntax is as follows, where classname is the name of the class you wish to be able to instantiate, and access:

import java.sql.classname

If you are unsure of what classes to import, you may use the following line to make all of the JDBC classes available:

import java.sql.*

Understand that importing the entire set of JDBC classes can introduce a great deal of extra overhead. For maximum efficiency, you should only import those classes which you know your application requires.