JDBC Architecture Overview

JDBC is similar in structure to ODBC. A JDBC application is composed of multiple layers, as shown in Figure 13.1.

Figure 13.1. JDBC architecture.


The topmost layer in this model is the Java application. Java applications are portable?you can run a Java application without modification on any system that has a Java runtime environment installed. A Java application that uses JDBC can talk to many databases with few, if any, modifications. Like ODBC, JDBC provides a consistent way to connect to a database, execute commands, and retrieve the results. Also like ODBC, JDBC does not enforce a common command language?you can use Oracle-specific syntax when connected to an Oracle server and PostgreSQL-specific syntax when connected to a PostgreSQL server. If you stick to a common subset, you can achieve remarkable portability for your applications.

The JDBC DriverManager

The JDBC DriverManager class is responsible for locating a JDBC driver needed by the application. When a client application requests a database connection, the request is expressed in the form of a URL (Uniform Resource Locator). A typical URL might look like jdbc:postgresql:movies. A JDBC URL is similar to the URLs that you use with a web browser (http://www.postgresql.org, for example). I'll explain the JDBC URL syntax in detail a bit later.

The JDBC Driver

As each driver is loaded into a Java Virtual Machine (VM), it registers itself with the JDBC DriverManager. When an application requests a connection, the DriverManager asks each Driver whether it can connect to the database specified in the given URL. As soon as it finds an appropriate Driver, the search stops and the Driver attempts to make a connection to the database. If the connection attempt fails, the Driver will throw a SQLException to the application. If the connection completes successfully, the Driver creates a Connection object and returns it to the application.

The JDBC 2.0 architecture introduced another method for establishing database connections: the DataSource. A DataSource is a named collection of connection properties that can be used to load a Driver and create a Connection. I do not discuss the DataSource class in this chapter because it is not yet part of the J2SE (Java 2 Standard Edition) standard; the DataSource class is a component of J2EE (Java 2 Enterprise Edition). The PostgreSQL JDBC driver does support the DataSource class.

The JDBC-Compliant Database

The bottom layer of the JDBC model is the database. The PostgreSQL Driver class (and other JDBC classes) translates application commands into PostgreSQL network requests and translates the results back into JDBC object form.

    Part II: Programming with PostgreSQL