The second step in establishing a connection is to have the appropriate driver connect to the DBMS. The following line of code illustrates the general idea:
Connection con = DriverManager.getConnection(url, "myLogin", "myPassword");
This step is also simple, with the hardest thing being what to supply for
url
. If you are using the JDBC-ODBC Bridge driver, the JDBC URL will start with
jdbc:odbc:
. The rest of the URL is generally your data source name or database system. So, if you are using ODBC to access an ODBC data source called "
Fred,
" for example, your JDBC URL could be
jdbc:odbc:Fred
. In place of "
myLogin
" you put the name you use to log in to the DBMS; in place of "
myPassword
" you put your password for the DBMS. So if you log in to your DBMS with a login name of "
Fernanda
" and a password of "
J8,
" just these two lines of code will establish a connection:
String url = "jdbc:odbc:Fred";
Connection con = DriverManager.getConnection(url, "Fernanda", "J8");
If you are using a JDBC driver developed by a third party, the documentation will tell you what subprotocol to use, that is, what to put after
jdbc:
in the JDBC URL. For example, if the driver developer has registered the name acme as the subprotocol, the first and second parts of the JDBC URL will be
jdbc:acme:
. The driver documentation will also give you guidelines for the rest of the JDBC URL. This last part of the JDBC URL supplies information for identifying the data source.
If one of the drivers you loaded recognizes the JDBC URL supplied to the method
DriverManager.getConnection
, that driver will establish a connection to the DBMS specified in the JDBC URL. The
DriverManager
class, true to its name, manages all of the details of establishing the connection for you behind the scenes. Unless you are writing a driver, you will probably never use any of the methods in the interface
Driver
, and the only
DriverManager
method you really need to know is
DriverManager.getConnection
.
The connection returned by the method
DriverManager.getConnection
is an open connection you can use to create JDBC statements that pass your SQL statements to the DBMS. In the previous example,
con
is an open connection, and we will use it in the examples that follow.