O'Reilly logo

Practical PostgreSQL by John C. Worsley, Joshua D. Drake

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Using the PostgreSQL Driver

This section describes the process for using the built-in 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 the Driver gets registered within your code. 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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required