java tutorial - JDBC Driver Class - java programming - learn java - java basics - java for beginners
DriverManager class
- The DriverManager is a static class in Java 2 Plaform, Standard Edition (J2SE) as well as Java SE Development Kit (JDK).
- DriverManager manages the set of Java Database Connectivity (JDBC) drivers that are available for an application to use.
- Applications can use multiple JDBC drivers concurrently if necessary.
- Each and every application specifies a JDBC driver by using a Uniform Resource Locator (URL).
- By passing a URL for a specific JDBC driver to the DriverManager, the application informs the DriverManager about which type of JDBC connection should be returned to the application.
- Before this can be done, the DriverManager should be made aware of the available JDBC drivers so it can hand out the connections. By making a call to the Class.forName method, it loads a class into the running Java virtual machine (JVM) based on its string name that is passed into the method. The given below is an example of the class.forName method being used to load the native JDBC driver:
Methods of DriverManager class
Method | Description |
---|---|
public static void registerDriver(Driver driver): | is used to register the given driver with DriverManager. |
public static void deregisterDriver(Driver driver): | is used to deregister the given driver (drop the driver from the list) with DriverManager. |
public static Connection getConnection(String url): | is used to establish the connection with the specified url. |
public static Connection getConnection (String url,String userName,String password): | is used to establish the connection with the specified url, username and password. |
Example:
Load the native JDBC driver
- JDBC drivers are designed to the DriverManager about themselves automatically when their driver implementation class loads.
- Just the once the line of code before mentioned that has been processed, then the native JDBC driver is offered for the DriverManager with which to work.
- The given below line of code requests a Connection object using the native JDBC URL:
Request a Connection object
- The simplest form of JDBC URL is a list of three values that are separated by colons.
- The first value in the list represents the protocol that is always jdbc for JDBC URLs.
- The second value is the sub protocol and db2 or db2iSeries which are used to specify the native JDBC driver.
- The third value is the system name to establish the connection to a specific system.
- There are two special values that can be used to connect to the local database.
- They are *LOCAL as well as localhost (both are case insensitive). A specific system name will also provided as follows: