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. ...

Get Practical PostgreSQL now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.