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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access