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 optimized for basic learning, practice and more. Examples are well checked and working examples available on this website but we can't give assurity for 100% correctness of all the content. This site under copyright content belongs to Onlinetpoint. You agree to have read and accepted our terms of use, cookie and privacy policy.