How to get the list of all drivers registered with the DriverManager using JDBC?


The java.sql.DriverManager class manages JDBC drivers in your application. This class maintains a list of required drivers and load them whenever it is initialized.

Therefore, you need to register the driver class before using it. However, you need to do it only once per application.

One way to register a driver class object to Driver manager is the registerDriver() method of the DriverManager class. To this method you need to pass the Driver object as a parameter.

//Instantiating a driver class Driver driver = new com.mysql.jdbc.Driver();
//Registering the Driver DriverManager.registerDriver(driver);

List of all the Drivers

You can get the list of all the drivers registered with this DriverManager class using the getDrivers() method of it. This method returns an Enumeration containing the list of drivers.

//Retrieving the list of all the Drivers
Enumeration<Driver> e = DriverManager.getDrivers();
//Printing the list
while(e.hasMoreElements()) {
   System.out.println(e.nextElement().getClass());
}

Following JDBC program registers a bunch of JDBC drivers using the registerDriver() method and, displays the list of them using the getDrivers() method.

Example

import java.sql.Driver;
import java.sql.DriverManager;
import java.util.Enumeration;
public class DriversList_DriverManager {
   public static void main(String args[])throws Exception {
      //Registering MySQL driver
      DriverManager.registerDriver(new com.mysql.jdbc.Driver());
      //Registering SQLite driver
      DriverManager.registerDriver(new org.sqlite.JDBC());
      //Registering Oracle driver
      DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
      //Registering Derby-client driver
      DriverManager.registerDriver(new org.apache.derby.jdbc.ClientDriver());
      //Registering Derby-autoloaded driver
      DriverManager.registerDriver(new org.apache.derby.jdbc.AutoloadedDriver());
      //Registering HSQLDb-JDBC driver
      DriverManager.registerDriver(new org.hsqldb.jdbc.JDBCDriver());
      System.out.println("List of all the Drivers registered with the DriverManager:");
      //Retrieving the list of all the Drivers
      Enumeration<Driver> e = DriverManager.getDrivers();
      //Printing the list
      while(e.hasMoreElements()) {
         System.out.println(e.nextElement().getClass());
      }
      System.out.println();
   }
}

Output

List of all the Drivers registered with the DriverManager:
class org.sqlite.JDBC
class org.apache.derby.jdbc.ClientDriver
class org.apache.derby.jdbc.AutoloadedDriver
class org.hsqldb.jdbc.JDBCDriver
class com.mysql.jdbc.Driver
class oracle.jdbc.driver.OracleDriver

Updated on: 30-Jul-2019

721 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements