Making a Connection
Once a driver is on your classpath, the standard way to open a connection to a database is
DriverManager.getConnection(url, user, password). It returns a Connection object,
which represents a live session with the database and is the starting point for everything else in JDBC.
DriverManager.getConnection
Example: Opening a Connection
import java.sql.*;
public class ConnectExample {
public static void main(String[] args) throws Exception {
Connection conn = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/coding_with_sonu", "root", "");
System.out.println("Connected!");
conn.close();
}
}
Anatomy of a JDBC URL
The URL string tells DriverManager which driver to use and how to reach the database. Breaking down
jdbc:mysql://localhost:3306/coding_with_sonu?useSSL=false&serverTimezone=UTC:
| Part | Value | Meaning |
|---|---|---|
| Protocol | jdbc:mysql: | Tells JDBC this is a MySQL connection |
| Host | localhost | Where the database server is running |
| Port | 3306 | The port MySQL is listening on |
| Database name | coding_with_sonu | The specific database/schema to use |
| Parameters | ?useSSL=false&serverTimezone=UTC | Optional driver settings, joined with & |
Always Close Your Connection
A Connection holds real resources — a network socket and server-side state. Forgetting to call
.close() leaks connections and can exhaust your database's connection pool over time. Calling it
manually works, but it's easy to skip when an exception is thrown partway through your code.
Try-With-Resources: the Recommended Pattern
Connection implements AutoCloseable, so the safest way to use one is inside a
try-with-resources block. The connection is closed automatically when the block ends — whether it finishes
normally or an exception is thrown.
Example: Try-With-Resources Connection
import java.sql.*;
public class TryWithResourcesExample {
public static void main(String[] args) {
try (Connection conn = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/coding_with_sonu", "root", "")) {
System.out.println("Connected!");
// conn.close() is called automatically here, even on exception
} catch (SQLException e) {
e.printStackTrace();
}
}
}
Connection, Statement, or ResultSet, reach for try-with-resources by default instead of a manual .close().Checking a Connection Is Still Valid
Connections can silently die (network blip, database restart). Before reusing a long-lived connection, you can
check conn.isValid(timeout), which pings the database and returns true or
false within the given timeout in seconds — handy for connection pools and health checks.