Use the JDBC DriverManager to connect to the DBMS.
Using the JDBC DriverManager
Before we can begin to use a JDBC driver, there is a little bit of housekeeping that needs to be performed. As is the case with any Java class that we intend to use, that class has to be loaded and instantiated.
The java.sql.DriverManager class, sometimes called the DriverManager, provides an access layer that can be used on top of different database drivers and used with an application.
JDBC Connection Process
The process for using the DriverManager to connect to the DBMS is two-fold. The first step is to load the appropriate driver class, so that the DriverManager can access it.
This has to be done only once in the life of the application and must be completed before attempting the first connection.
The second step is performed each time a new connection is needed.
Of course, the code is customized to include the specific JDBC URL, user ID, and password. This simple line of code creates an open connection ready to be used to access the database.
The Slideshow below illustrates the JDBC DriverManager connection process and will prepare you for the exercise that follows this lesson.
You have learned that JDBC achieves its functionality through a set of Java interfaces, each implemented differently by specific database vendors. JDBC includes JDBC drivers,
which are a set of classes that implement the JDBC interfaces for a specific database engine.
Now that you have an overall understanding of the JDBC API package, let's turn to the subject of obtaining a database connection. specifically, loading a database driver and opening the connection.
The vendor and the network protocol define the implementation of a database connection. The interface, in the JDBC 2.0 core API, that represents the connection is: java.sql.Connection.
Interestingly, you can use different JDBC drivers in one application to obtain one or more connections for one or more databases. To accomplish this, just instantiate the appropriate database driver for each of the databases, such as:
View the code below to see a generic example of using the DriverManager to retrieve a connection object.
Connection con = DriverManager.getConnnection(url, "myUsername", "myPassword");
The two main elements related to obtaining a database connection are the JDBC URLs and the java.sql.DriverManager class, referred to as the DriverManager.
You will learn how to modify and compile this code to make it work for your specific customer and user needs.
In the next lesson, you will learn how to put all these pieces together into a working program.