DriverManager Class in Java
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
| Method | Description |
|---|---|
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
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());
}
}
}URL only: ONE
User, password: NAVIKA
Properties: SRIHITHA
Login timeout: 5 s
No suitable driver found for jdbc:oracle:thin:@localhost:1521:xe
SQLState: 08001Explanation:
- URL only is enough when the database needs no login, or the URL itself carries the credentials.
- URL, user and password is the most common form. H2 creates the user on first use and reports names in upper case.
Propertiesis useful when the settings come from a file; drivers also accept their own extra options this way.setLoginTimeout(5)tells drivers to give up after 5 seconds instead of waiting indefinitely for an unreachable server.- The Oracle URL fails because no Oracle driver is on the class path. The
SQLExceptioncarries an SQLState code;08001means "unable to establish a connection".
How DriverManager Chooses a Driver
- 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). - For
getConnection(url), it asks each registered driver, in turn, to connect. - A driver that doesn't recognize the URL prefix returns
null, and the next one is tried. - The first driver that returns a connection wins. If none does, you get "No suitable driver found".
DriverManager vs DataSource
| Point | DriverManager | DataSource |
|---|---|---|
| Creates | A new physical connection on every call | Usually hands out a connection from a pool |
| Configuration | URL and credentials in the calling code | Set up once, outside the code that uses it |
| Suited to | Small programs, scripts, learning | Applications and servers |
| Extras | None | Pooling, 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
- Easy: Print the class name of every registered driver using
DriverManager.drivers(). - Harder: Load the URL, user and password from a
.propertiesfile withProperties.loadand connect using thegetConnection(url, properties)form.
Key Takeaways
Was this tutorial helpful?