JDBC Basics

Basic Java
≈ 2 min read

What working through JDBC looks like

JDBC is not a separate database and it does not invent its own query language. A Java application still sends ordinary SQL, while JDBC provides standard interfaces through which the code opens a connection, executes a command, and receives a result.

A JDBC driver sits between the application and a specific DBMS. It implements the JDBC interfaces and knows how to communicate with PostgreSQL, MySQL, Oracle Database, or another supported system.

The minimal query path

String url = "jdbc:postgresql://localhost:5432/app";

try (Connection connection = DriverManager.getConnection(url, "app", "secret");
     PreparedStatement statement = connection.prepareStatement(
             "SELECT name FROM users WHERE id = ?")) {

    statement.setLong(1, 42);

    try (ResultSet result = statement.executeQuery()) {
        if (result.next()) {
            System.out.println(result.getString("name"));
        }
    }
}

This shows the entire JDBC chain. DriverManager helps obtain a connection, Connection represents work with the database, PreparedStatement holds SQL with a parameter, and ResultSet lets you read the returned rows. We will examine each of these objects separately next.

The driver must be available to the application

For a real database, the project dependencies must contain an appropriate JDBC driver. Modern drivers are discovered automatically, so an ordinary application generally does not need to call Class.forName() manually just to register a driver.

JDBC is low-level database access. The application writes SQL itself and explicitly works with connections and results. Higher-level tools can later be built on top of these ideas, but understanding JDBC helps you see what happens underneath them.