Connecting to a JDBC Database
Problem
You need to connect to the database.
Solution
Use DriverManager.getConnection( )
.
Discussion
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
Type |
Name |
Notes |
---|---|---|
1 |
JDBC-ODBC Bridge |
Provides JDBC API access. |
2 |
Java and Native Driver |
Java code calls Native DB driver. |
3 |
Java and Middleware |
Java contacts middleware server. |
4 |
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 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.