Java JDBC DriverManager Class Example with MySQL Database

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().
In short, DriverManager Class provides basic service for managing a set of JDBC drivers.
From JDBC 4.0, applications no longer need to explicitly load JDBC drivers using Class.forName(). When the method getConnection is called, the DriverManager will attempt to locate a suitable driver from amongst those loaded at initialization and those loaded explicitly using the same classloader as the current applet or application.
We are going to use the MySQL database to demonstrate the usage of the JDBC DriverManager Class.

Technologies used

  • JDK - 1.8 or later
  • MySQL - 5.7.12
  • IDE - Eclipse Neon
  • JDBC API - 4.2

DriverManager Class Diagram

DriverManager Class Commonly used methods

  • static void deregisterDriver(Driver driver) - Removes the specified driver from the DriverManager's list of registered drivers.
  • static Connection getConnection(String url) - Attempts to establish a connection to the given database URL.
  • static Connection getConnection(String url, Properties info) - Attempts to establish a connection to the given database URL.
  • static Connection getConnection(String url, String user, String password) - Attempts to establish a connection to the given database URL.
  • static Driver getDriver(String url) - Attempts to locate a driver that understands the given URL.
  • static Enumeration getDrivers() - Retrieves an Enumeration with all of the currently loaded JDBC drivers to which the current caller has access.
  • static void registerDriver(Driver driver) - Registers the given driver with the DriverManager.

DriverManager Class Examples

1. Java DriverManager.registerDriver(Driver driver) Method

The registerDriver(Driver driver) method of DriverManager class registers the given driver in the DriverManager's list. If the driver is null, it returns the NullPointerException.
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!");
  }
}
Output:
Driver successfully registered!

2. Java DriverManager.registerDriver(Driver driver) Method

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

3. Connection getConnection(String URL, String user, String password)

This method is used to attempts to establish a connection to the given database URL.
try (Connection connection = DriverManager
    .getConnection("jdbc:mysql://localhost:3306/mysql_database?useSSL=false", "root", "root");

   // Step 2:Create a statement using connection object
   Statement statement = connection.createStatement();) {

    // Step 3: Execute the query or update query
    statement.execute(createTableSQL);
    } catch (SQLException e) {a
}

4. Enumeration java.sql.DriverManager.getDrivers() Method

Retrieves an Enumeration with all of the currently loaded JDBC drivers to which the current caller has access.
package com.javaguides.jdbc.statement.examples.packages;

import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Enumeration;

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 !");

        Enumeration < Driver > iterator = DriverManager.getDrivers();
        while (iterator.hasMoreElements()) {
            Driver driver2 = (Driver) iterator.nextElement();
            System.out.println(driver2);
        }
    }
}
Output:
Driver successfully registered !
com.mysql.fabric.jdbc.FabricMySQLDriver@135fbaa4
com.mysql.jdbc.Driver@45ee12a7
com.mysql.jdbc.Driver@330bedb4

5. void java.sql.DriverManager.setLoginTimeout(int seconds) Method

Sets the maximum time in seconds that a driver will wait while attempting to connect to a database once the driver has been identified.
package com.javaguides.jdbc.statement.examples.packages;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class DriverManagerExamples {
    public static void main(String[] args) throws SQLException {

        DriverManager.setLoginTimeout(10); //to set login timeout  
        try (Connection connection = DriverManager
            .getConnection("jdbc:mysql://localhost:3306/mysql_database?useSSL=false", "root", "root")) {
            System.out.println("Connection created");
            //to get login timeout  
            System.out.println("your login timeout is = " + DriverManager.getLoginTimeout());
        }
        System.out.println("Connection auto closed");
    }
}
Output:
Connection created
your login timeout is = 10
Connection auto closed

JDBC Statement Interface Examples

          Example to create a table using a Statement interface.
          Example to insert multiple records in a table using Statement interface.
          Example to update a record in a table using Statement interface.
          Example to retrieve records from a table using Statement interface.
          Example to delete a record from a table using a Statement interface.
          Example to insert records in a batch process via Statement interface.
          Example to update records in a batch process via Statement interface.

JDBC PreparedStatement Interface Examples

         Example to insert a record in a table using the PreparedStatement interface.
         Example to update a record in a table using the PreparedStatement interface.
          Example to retrieve records from a table using the PreparedStatement interface.
          Example to pass a list of values to IN clause using PreparedStatement interface.
          Example to insert records in a batch process via PreparedStatement interface.
          Example to update records in a batch process via PreparedStatement interface.

Free Spring Boot Tutorial | Full In-depth Course | Learn Spring Boot in 10 Hours


Watch this course on YouTube at Spring Boot Tutorial | Fee 10 Hours Full Course

Comments

  1. Thankyou for this wondrous post, I am glad I observed this website on yahoo.Dubai rent a car with driver

    ReplyDelete
  2. Nice to be visiting your blog once more, it has been months for me. Hire Cheap Cars With Driver Dubai

    ReplyDelete

Post a Comment