Java Reference
In-Depth Information
Connecting to a JDBC Data Source
To connect to a JDBC data source, its name must be represented as a URL of the following
format:
jdbc:<subprotocol>:<dsn>
All JDBC URLs start with jdbc. The subprotocol is actually determined by the driver you
are using. For example, the bridge driver we will use has a subprotocol ODBC. The DSN is
whatever the name is of the data source.
For example, the following URL represents a data source named moviesDSN, which is
being accessed using the bridge driver:
jdbc:odbc:moviesDSN
The following URL represents the same data source being accessed from a type 3 dri-
ver from a company called JDataConnect:
jdbc:JDataConnect://localhost/musicDSN
JDBC URLs are driver dependent, so be sure to check any documentation that comes
with your driver for determining the proper URL syntax.
Using the DriverManager Class
There are two steps involved in connecting to a database using the Driver-
Manager class: Load the appropriate JDBC driver, and then invoke the
getConnection() method of the DriverManager class.
The driver is loaded when the corresponding bytecode class is loaded by the
JVM, so you need to make sure the driver class is loaded. One way to do this is
to use the Class.forName() method. For example, the following statement loads
the sun.jdbc.odbc.JdbcOdbcDriver type 1 driver that comes with the J2SE:
Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
After the driver is loaded, the connection is made using one of the following
methods in the DriverManager class:
public static Connection getConnection(String url) throws SQLException.
Establishes a connection to the given database. The DriverManager will
select an appropriate JDBC driver if more than one has been loaded.
public static Connection getConnection(String url, String user, String
password) throws SQLException. Same as the previous version,
except that a username and password are passed in if the database
requires authentication.
Search WWH ::




Custom Search