Connecting to a JDBC Database


You need to connect to the database.


Use DriverManager.getConnection( ).


The static method DriverManager.getConnection( ) lets you connect to the database using a URL-like syntax for the database name (for example, jdbc:dbmsnetproto://server:4567/mydatabase) and a login name and password. The “dbURL” that you give must begin with jdbc:. The rest of it can be in whatever form the driver vendor’s documentation requires, and is checked by the driver. The DriverManager asks each driver you have loaded (if you’ve loaded one) to see if it can handle a URL of the form you provided. The first one that responds in the affirmative gets to handle the connection, and its connect( ) method is called for you (by DriverManager.getConnection( )).

There are four types of drivers defined by Sun (not in the JDBC specification, but in their less formal documentation); these are shown in Table 20-1.

Table 20-1. JDBC driver types






Provides JDBC API access.


Java and Native Driver

Java code calls Native DB driver.


Java and Middleware

Java contacts middleware server.


Pure Java

Java contacts (possibly remote) DB directly.

Table 20-2 shows some interesting drivers. I’ll use the ODBC bridge driver and IDB in examples for this chapter. Some drivers work only locally (like the JDBC-ODBC bridge), while others work across a network. For details on different types of drivers, please refer to the books ...

Get Java Cookbook now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.