Skip to content
AITroveRead. Build. Understand.
Make this comfortable

Java JDBC query timeout: bound a statement without claiming a whole-request deadline

Last updated: 5 Oct 20265 min read
tutorial
AdvancedBy AITrove Editorial

Statement.setQueryTimeout asks the driver to limit execution time for that statement in seconds. It is not a complete deadline for connection acquisition, network stalls, or all work in a request.

Operational contract

This method sets a three-second query timeout before executing a parameterized lookup. It closes the ResultSet and PreparedStatement in one scope, returns at most one status value, and rejects a second matching row. A driver may attempt to cancel a timed-out statement and report SQLTimeoutException; cancellation and server behavior are driver-dependent. A connection-pool acquisition timeout and Connection.setNetworkTimeout govern different waiting phases. Never assume this setter interrupts every JDBC call at exactly three seconds.

Failure case

A shipment-status query waits on a database lock. The statement timeout may terminate the query and surface an exception; the outer request must still decide whether to retry. A request that spent five seconds waiting for a pool connection before creating the statement was never protected by this three-second setting.

Java code

Java
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class TimedShipmentLookup {
    public static String status(Connection connection, long shipmentId) throws SQLException {
        try (PreparedStatement statement = connection.prepareStatement(
                "SELECT status FROM shipments WHERE shipment_id = ?")) {
            statement.setQueryTimeout(3);
            statement.setLong(1, shipmentId);
            try (ResultSet rows = statement.executeQuery()) {
                if (!rows.next()) return null;
                String status = rows.getString(1);
                if (rows.next()) throw new SQLException("Duplicate shipment ID");
                return status;
            }
        }
    }
}

Performance and ownership cost

The Java cursor retains O(1) application data, while indexed lookup and lock wait determine database cost. The timeout limits one driver operation according to its implementation; it does not cap total request wall time or establish idempotent retry semantics.

Common Mistakes

  • Do not count pool wait or connection setup inside a statement timeout.
  • Do not assume timed-out SQL had no side effect without checking transaction state.
  • Do not leave result sets open after timeout or error.

Connected lessons

java
transaction and capability boundaries
jdbc-query-timeout-budget
Storage details