Follow Techotopia on Twitter

On-line Guides
All Guides
eBook Store
iOS / Android
Linux for Beginners
Office Productivity
Linux Installation
Linux Security
Linux Utilities
Linux Virtualization
Linux Kernel
System/Network Admin
Programming
Scripting Languages
Development Tools
Web Development
GUI Toolkits/Desktop
Databases
Mail Systems
openSolaris
Eclipse Documentation
Techotopia.com
Virtuatopia.com
Answertopia.com

How To Guides
Virtualization
General System Admin
Linux Security
Linux Filesystems
Web Servers
Graphics & Desktop
PC Hardware
Windows
Problem Solutions
Privacy Policy

  




 

 

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 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 .jar file is not in your classpath.

Once you have registered the Driver 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://localhost/booktown, meaning you are connecting to host localhost and database booktown. 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 booktown 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://localhost/booktown",
                                    "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 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 to your program:

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 that you know your application requires.


 
 
  Published courtesy of O'Reilly Design by Interspire