JDBC DriverManager Class


The DriverManager class serves as the central point in the JDBC API of the java.sql package to handle JDBC drivers and facilitate database connections for Java applications.


Key Responsibilities

  • Loads JDBC drivers
  • Maintains a list of registered drivers
  • Establishes database connections
  • Throws errors when connection fails

Package

import java.sql.DriverManager; 

Methods

Method Description
getConnection(String url) Establishes a connection using URL only
getConnection(String url, String user, String password) Establishes a connection with authentication
registerDriver(Driver driver) Manually registers a JDBC driver
deregisterDriver(Driver driver) Removes a driver from the list
getDrivers() Returns an Enumeration of all loaded drivers
setLoginTimeout(int seconds) Sets login timeout duration
getLoginTimeout() Gets the login timeout value

Syntax

Connection con = DriverManager.getConnection(
    "jdbc:mysql://localhost:3306/testdb", "root", "password"); 

Example

 import java.sql.*;

public class DriverManagerExample {
    public static void main(String[] args) {
        try {
            // Step 1: Load the JDBC driver
            Class.forName("com.mysql.cj.jdbc.Driver");

            // Step 2: Get a connection using DriverManager
            Connection con = DriverManager.getConnection(
                "jdbc:mysql://localhost:3306/testdb",
                "root",
                "password"
            );

            // Step 3: Create a statement
            Statement stmt = con.createStatement();

            // Step 4: Execute query
            ResultSet rs = stmt.executeQuery("SELECT * FROM employees");

            // Step 5: Process result set
            while (rs.next()) {
                System.out.println(rs.getInt("id") + " - " + rs.getString("name"));
            }

            // Step 6: Close connection
            con.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

notepad

Manual driver registration is typically unnecessary. The JDBC driver JAR file automatically registers itself when found in the classpath by using META-INF/services/java.sql.Driver




OnlineTpoint is a website that is meant to offer basic knowledge, practice and learning materials. Though all the examples have been tested and verified, we cannot ensure the correctness or completeness of all the information on our website. All contents published on this website are subject to copyright and are owned by OnlineTpoint. By using this website, you agree that you have read and understood our Terms of Use, Cookie Policy and Privacy Policy.