DriverManager Class in Java

Naveen AnamaneniUpdated · 6 min read

The DriverManager class is the basic service for managing JDBC drivers and the simplest way to get a database connection. It keeps a list of the drivers that are available, and when you ask for a connection it tries each one until it finds a driver that understands your URL. All of its methods are static; you never create a DriverManager object. In this lesson, you will learn its methods, the three ways to call getConnection, how it chooses a driver, and why larger applications use a DataSource instead.

Methods

MethodDescription
getConnection(url)It is used to open a connection using only a URL.
getConnection(url, user, password)It opens a connection with a user name and password.
getConnection(url, properties)It opens a connection with settings held in a Properties object.
getDriver(url)It returns the driver that understands the URL.
drivers()It returns a stream of all registered drivers.
registerDriver(driver), deregisterDriver(driver)They add or remove a driver by hand (rarely needed).
setLoginTimeout(seconds), getLoginTimeout()They set and read how long to wait when connecting.

Example: Three Ways to Connect

Manager.java▶ Try it
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
 
public class Manager {
    public static void main(String[] args) throws Exception {
        // 1. URL only.
        try (Connection a = DriverManager.getConnection("jdbc:h2:mem:one")) {
            System.out.println("URL only:       " + a.getCatalog());
        }
        // 2. URL, user and password.
        try (Connection b = DriverManager.getConnection(
                "jdbc:h2:mem:two", "navika", "secret")) {
            System.out.println("User, password: "
                + b.getMetaData().getUserName());
        }
        // 3. URL and a Properties object.
        Properties props = new Properties();
        props.setProperty("user", "srihitha");
        props.setProperty("password", "secret");
        try (Connection c =
                 DriverManager.getConnection("jdbc:h2:mem:three", props)) {
            System.out.println("Properties:     "
                + c.getMetaData().getUserName());
        }
 
        DriverManager.setLoginTimeout(5);
        System.out.println("Login timeout:  "
            + DriverManager.getLoginTimeout() + " s");
 
        try {
            DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe");
        } catch (SQLException e) {
            System.out.println(e.getMessage());
            System.out.println("SQLState: " + e.getSQLState());
        }
    }
}
Output
URL only:       ONE
User, password: NAVIKA
Properties:     SRIHITHA
Login timeout:  5 s
No suitable driver found for jdbc:oracle:thin:@localhost:1521:xe
SQLState: 08001

Explanation:

  1. URL only is enough when the database needs no login, or the URL itself carries the credentials.
  2. URL, user and password is the most common form. H2 creates the user on first use and reports names in upper case.
  3. Properties is useful when the settings come from a file; drivers also accept their own extra options this way.
  4. setLoginTimeout(5) tells drivers to give up after 5 seconds instead of waiting indefinitely for an unreachable server.
  5. The Oracle URL fails because no Oracle driver is on the class path. The SQLException carries an SQLState code; 08001 means "unable to establish a connection".

How DriverManager Chooses a Driver

  1. At startup it loads every driver found on the class path (each driver JAR lists its driver class in META-INF/services/java.sql.Driver).
  2. For getConnection(url), it asks each registered driver, in turn, to connect.
  3. A driver that doesn't recognize the URL prefix returns null, and the next one is tried.
  4. The first driver that returns a connection wins. If none does, you get "No suitable driver found".

DriverManager vs DataSource

PointDriverManagerDataSource
CreatesA new physical connection on every callUsually hands out a connection from a pool
ConfigurationURL and credentials in the calling codeSet up once, outside the code that uses it
Suited toSmall programs, scripts, learningApplications and servers
ExtrasNonePooling, distributed transactions

Opening a connection involves a network handshake and a login, which can take many milliseconds. An application that does it for every request is slow, so real applications use a pooled DataSource (see "Connection Pooling and DataSource in JDBC").

Common Mistakes

Calling getConnection for every query in a busy application. Use a connection pool.

No login timeout. An unreachable database can make the program hang for a long time.

Registering the driver by hand as well. With a JDBC 4 driver this is unnecessary and can register it twice.

Interview Corner

What is the role of DriverManager in JDBC?

DriverManager manages the set of registered JDBC drivers and creates connections. Drivers on the class path are loaded automatically through the service provider mechanism. When getConnection(url, ...) is called, it asks each registered driver to connect and returns the connection from the first driver that accepts the URL, or throws SQLException ("No suitable driver found") if none does. It also provides login timeout and logging settings.

What is the difference between DriverManager and DataSource?

DriverManager.getConnection opens a new physical connection each time and needs the URL and credentials in the calling code. A DataSource is an object configured once that supplies connections, typically from a connection pool, and can also support distributed transactions. DataSource is preferred in applications because pooling avoids the cost of opening connections repeatedly and keeps configuration out of the code.

Practice

  1. Easy: Print the class name of every registered driver using DriverManager.drivers().
  2. Harder: Load the URL, user and password from a .properties file with Properties.load and connect using the getConnection(url, properties) form.

Quick check: DriverManager

4 questions
1How do you create a DriverManager?
2What does getConnection do each time it is called?
3How does DriverManager pick a driver?
4What does SQLState 08001 indicate?

Key Takeaways

Was this tutorial helpful?

Lesson 487 of 578