Site icon TestingDocs.com

JDBC DriverManager Class

Overview

JDBC DriverManager class is an important class and the backbone of JDBC architecture. DriverManager is the basic service for managing a set of JDBC drivers installed on the system.

JDBC DriverManager

The JDBC DriverManager defines objects which connect Java Applications to a JDBC driver. It is a basic service used to manage different types of JDBC database drivers.

Some of the commonly used methods of the class are as follows:

deregisterDriver(Driver driver): This method drops the driver from the list of drivers registered in the DriverManager class.
registerDriver(Driver driver): This method registers the driver with the DriverManager
getConnection(String url): The method tries to establish the connection to a given database URL.
getConnection(String url, String user, String password): This method tries to establish the connection to a given database URL.
getDriver(String url): The method attempts to locate the driver by the given string.
getDrivers(): This method retrieves the enumeration of the drivers which has been registered with the DriverManager class.

getConnection()

When the method getConnection() is invoked, DriverManager will attempt to locate and load a suitable JDBC driver. The getConnection() method establishes a connection to a given database URL.

Import DriverManager

We can import the class in the Java application from the java.sql package.

import java.sql.DriverManager;

Code Example

String driverName = "oracle.jdbc.driver.OracleDriver";
String hostName = "localhost";
String portNumber = "1521";
String serviceName = "orclpdb.localdomain";
String username="scott";
String password="tiger";
String url = "jdbc:oracle:thin:@//" + hostName + ":" + 
     	portNumber + "/" + serviceName ;
try {
    // Load the Oracle JDBC driver
    Class.forName(driverName);
Connection connection = 
DriverManager.getConnection(url, username, password);
    } catch (Exception exp) {
    System.out.println("Exception : "
	+exp.getMessage());
    }

 

JDBC driver initialization is done lazily by the DriverManager. It looks up the service providers using the thread context class loader. DriverManager class will attempt to load available JDBC drivers by using jdbc.drivers system property. The system property can contain a colon-separated list of fully qualified class names of the JDBC drivers.

 

 

The following code loads the Oracle JDBC thin driver and the DriverManager.getConnection() method attempts to establish a database connection to the SCOTT scheme in the pluggable database orclpdb. If the connection cannot connect to the database an exception SQLException is thrown.

Java Tutorials

Java Tutorial on this website:

https://www.testingdocs.com/java-tutorial/

For more information on Java, visit the official website :

https://www.oracle.com/java/

More information about Oracle Database:

https://www.oracle.com/database/

Exit mobile version