How do I create a database connection with DriverManager?

Creating a database connection with DriverManager is the standard way to establish a session with a database in JDBC.

1. The Essential Formula

To get a connection, you call DriverManager.getConnection() using a Connection URL, a username, and a password.

Connection connection = DriverManager.getConnection(url, username, password);

2. Implementation Example

In modern Java (JDBC 4.0+), you don’t need to manually load the driver class with Class.forName(). The DriverManager will automatically find the driver on your classpath.

It is best practice to use a try-with-resources block to ensure the connection is closed automatically, even if an error occurs.

package org.kodejava.jdbc;

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

public class DatabaseConnection {
    public static void main(String[] args) {
        // 1. Define connection parameters
        String url = "jdbc:mysql://localhost:3306/your_database";
        String user = "your_username";
        String password = "your_password";

        // 2. Establish connection within try-with-resources
        try (Connection conn = DriverManager.getConnection(url, user, password)) {
            if (conn != null) {
                System.out.println("Successfully connected to the database!");
            }
        } catch (SQLException e) {
            System.err.println("Connection failed!");
            e.printStackTrace();
        }
    }
}

3. Common Connection URLs

The format of the URL varies depending on the database you are using:

  • MySQL: jdbc:mysql://localhost:3306/db_name
  • PostgreSQL: jdbc:postgresql://localhost:5432/db_name
  • Oracle: jdbc:oracle:thin:@localhost:1521:xe
  • SQL Server: jdbc:sqlserver://localhost:1433;databaseName=db_name

Key Points to Remember:

  • Classpath: Ensure the database driver JAR (like mysql-connector-j or postgresql) is in your project’s dependencies.
  • Exception Handling: Database operations always throw a SQLException, so they must be inside a try-catch block.
  • Security Tip: Avoid hardcoding passwords in your source code. Use environment variables or configuration files instead.

How to establish connection to a database using Properties object?

In the following code snippet, you will see how to pass some connection arguments when connecting to a database. To do this, we can use the java.util.Properties class. We can put some key value pairs as a connection arguments to the Properties object
before we pass this information into the DriverManager class.

Let’s see the example below:

package org.kodejava.jdbc;

import java.sql.*;
import java.util.Properties;

public class GetConnectionWithProperties {
    private static final String URL = "jdbc:mysql://localhost/kodejava";
    private static final String USERNAME = "kodejava";
    private static final String PASSWORD = "s3cr*t";

    public static void main(String[] args) {
        GetConnectionWithProperties demo = new GetConnectionWithProperties();
        try (Connection connection = demo.getConnection()) {
            // do something with the connection.
            Statement stmt = connection.createStatement();
            ResultSet rs = stmt.executeQuery("SELECT * FROM product");
            while (rs.next()) {
                System.out.println("Code = " + rs.getString("code"));
                System.out.println("Name = " + rs.getString("name"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    private Connection getConnection() throws SQLException {
        Properties connectionProps = new Properties();
        connectionProps.put("user", USERNAME);
        connectionProps.put("password", PASSWORD);

        Connection connection = DriverManager.getConnection(URL, connectionProps);
        System.out.println("Connected to database.");
        return connection;
    }
}

Maven Dependencies

<dependency>
    <groupId>com.mysql</groupId>
    <artifactId>mysql-connector-j</artifactId>
    <version>8.4.0</version>
</dependency>

Maven Central

How do I check whether a driver is JDBC compliant?

package org.kodejava.jdbc;

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

public class JDBCCompliant {
    private static final String URL = "jdbc:mysql://localhost/kodejava";

    public static void main(String[] args) {
        try {
            Driver driver = DriverManager.getDriver(URL);

            // Check if the driver is a genuine JDBC compliant driver.
            if (driver.jdbcCompliant()) {
                System.out.println("A genuine JDBC compliant driver");
            } else {
                System.out.println("Not a genuine JDBC compliant driver");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

Maven Dependencies

<dependency>
    <groupId>com.mysql</groupId>
    <artifactId>mysql-connector-j</artifactId>
    <version>8.4.0</version>
</dependency>

Maven Central