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:

PartValueMeaning
Protocoljdbc:mysql:Tells JDBC this is a MySQL connection
HostlocalhostWhere the database server is running
Port3306The port MySQL is listening on
Database namecoding_with_sonuThe specific database/schema to use
Parameters?useSSL=false&serverTimezone=UTCOptional 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();
    }
  }
}
Rule of thumb: whenever you open a 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.

Next up: Head to Statement Types to see the three ways JDBC lets you actually run SQL.