Connection

Basic Java
≈ 2 min read

Connection is an active context for working with the database

Connection represents a connection between the application and a specific database. It is used to create SQL commands, configure transactions, and request information about the connection. Almost all further JDBC work starts with this object.

try (Connection connection = DriverManager.getConnection(url, user, password)) {
    System.out.println(connection.getAutoCommit());
}

A connection is a resource, so it must be closed after use. The familiar try-with-resources does this automatically and is especially convenient for small JDBC examples. In server applications, a connection often comes from a pool, but the rule stays the same: the acquired resource must be returned to its owner promptly.

Connection creates commands

The Connection itself usually does not contain the SQL to execute. It creates objects for specific commands — most commonly PreparedStatement.

try (PreparedStatement statement = connection.prepareStatement(
        "UPDATE users SET active = ? WHERE id = ?")) {
    statement.setBoolean(1, true);
    statement.setLong(2, 42);
    statement.executeUpdate();
}

The connection state affects subsequent operations

A Connection has settings that change the behavior of commands executed through it, for example auto-commit mode, transaction isolation level, and the read-only flag. So a connection is not just a “wire to the database”; it is an object with state.

Do not treat Connection as a long-lived global object. Connections are limited resources and can be broken. Code usually obtains a connection for a particular unit of work, uses it, and then closes it or returns it to the pool.