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-jorpostgresql) is in your project’s dependencies. - Exception Handling: Database operations always throw a
SQLException, so they must be inside atry-catchblock. - Security Tip: Avoid hardcoding passwords in your source code. Use environment variables or configuration files instead.
