Java JDBC DriverManager Example

The DriverManager class acts as an interface between the user and drivers. It keeps track of the drivers that are available and handles establishing a connection between a database and the appropriate driver. 

The DriverManager class maintains a list of Driver classes that have registered themselves by calling the method DriverManager.registerDriver().

Java DriverManager.registerDriver(Driver driver) Example

The registerDriver(Driver driver) method of DriverManager class registers the given driver in the DriverManager's list. DriverAction is used when DriverManager.deregisterDriver is called:
package com.javaguides.jdbc.statement.examples.packages;

import java.sql.Driver;
import java.sql.DriverAction;
import java.sql.DriverManager;
import java.sql.SQLException;

public class DriverManagerExamples {
    public static void main(String[] args) throws SQLException {
        Driver driver = new com.mysql.jdbc.Driver();
        DriverManager.registerDriver(driver);
        System.out.println("Driver successfully registered !");

        DeRegisterDriver deRegisterDriver = new DeRegisterDriver(driver);
        deRegisterDriver.deregister();
    }
}

class DeRegisterDriver implements DriverAction {

    private Driver driver;
    DeRegisterDriver(Driver driver) {
        this.driver = driver;
    }

    @Override
    public void deregister() {
        try {
            DriverManager.deregisterDriver(driver);
            System.out.println("DeregisterDriver successfully");
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}
Output:
Driver successfully registered !
DeregisterDriver successfully

Learn more about JDBC DriverManager at https://www.javaguides.net/2018/10/jdbc-drivermanager-class.html

References

https://www.javaguides.net/2018/10/jdbc-drivermanager-class.html


Comments