Lesson · JDBC
JDBC Fundamentals: connection, statement, cursor, close
16 min readFundamentals
JDBC is a specification in java.sql, plus one driver per database that implements it. This lesson walks the object lifecycle everything else sits on: get a Connection, prepare a statement, bind values as data, walk a ResultSet cursor, and close it all in reverse.
What JDBC actually is
Connections are the first thing to go wrong when JDBC code leaves a laptop. A demo opens one per call and never closes it, which works until the database refuses new sessions; a query built by pasting user input into SQL works until someone types a quote. Both failures come from the same place: not knowing the objects and who owns them.
JDBC itself is a specification, not a library. It defines interfaces in java.sql and javax.sql, and each database ships a driver that implements them, so your code compiles against the interfaces while the driver speaks the wire protocol. Drivers register themselves through the ServiceLoader since JDBC 4, which is why Class.forName("org.postgresql.Driver") is a relic you can delete. The jdbc: prefix in a URL is a driver convention: jdbc:postgresql://localhost:5432/shop and jdbc:mysql://... are grammars each driver owns.
Two entry points hand you a connection. DriverManager.getConnection is the old one, and every call typically opens a fresh physical connection with TCP, authentication and session setup included in the price. DataSource is the modern one: configuration and pooling behind an interface, with no connection strings scattered through the code.
| DriverManager | DataSource | |
|---|---|---|
| What it returns | A new physical connection per call | A connection usually borrowed from a pool |
| Configuration | URL, user and password at each call site | Configured once at startup, then injected |
| Where it fits | Scripts, small tools, one-off utilities | Anything that serves requests |
Write application code against DataSource, not DriverManager. It costs nothing and buys pooling, one configuration point, and behaviour you can swap in tests.
The lifecycle: get, use, close
Every JDBC interaction is the same short pipeline: get a Connection, create a statement, execute it, read the ResultSet, close everything. The closes happen in reverse order of acquisition, and try-with-resources enforces exactly that.
Two facts bite people. A Connection is not thread-safe, so one connection belongs to one thread at a time. And close is mandatory: a leaked connection is a session the database server keeps reserving for you until something times out, which surfaces as too many connections long before the JVM notices memory pressure.
Once a pool is in the picture, close changes meaning slightly: it returns the connection to the pool instead of ending a physical session. Same code, much better economics.
// dataSource is a pooled javax.sql.DataSource, configured once at startup try (Connection conn = dataSource.getConnection(); PreparedStatement ps = conn.prepareStatement( "SELECT id, name FROM customers WHERE country = ?")) { ps.setString(1, "JP"); try (ResultSet rs = ps.executeQuery()) { while (rs.next()) { // the cursor starts before row 1 System.out.println(rs.getLong("id") + " " + rs.getString("name")); } } // ResultSet closed first } // then the statement, then the connection
Acquire in order, release in reverse, and let try-with-resources be the only close() you write. If a Connection variable is visible outside a try block, that is usually the bug.
Statement families and which execute to call
The API gives you three statements, and the choice is about who controls the SQL text and when it is fixed. Use the first only for SQL you fully control.
| Method | Use for | Returns |
|---|---|---|
| executeQuery | SELECT | a ResultSet |
| executeUpdate | INSERT, UPDATE, DELETE, DDL | an int row count (0 for DDL) |
| execute | anything when the kind is unknown in advance | a boolean: true means a ResultSet is available |
- Statement: SQL text assembled per call. Fine for DDL and fixed one-off statements; the wrong tool the moment a value comes from outside the program.
- PreparedStatement: SQL text with
?placeholders, sent to the server up front. Typed binding through setters, safe by construction, reusable across calls, and many drivers keep the server-side plan. - CallableStatement: stored procedures and functions, with their own call syntax for in, out and in-out parameters.
executeQuery for reads, executeUpdate for writes, execute when you genuinely do not know. Choosing the wrong one fails loudly, which is the good news.
Binding: values are data, never SQL text
PreparedStatement parameters are positions, not names: ? number one, two and so on, counted from 1. Binding is typed: setInt, setString, setBigDecimal, and setObject with the target class for java.time values (JDBC 4.2, Java 8: setObject(n, LocalDate.now())).
A NULL needs a type when the driver cannot infer one: setNull(n, Types.DATE). And the same 1-based counting trips people on the read side, because ResultSet columns are indexed from 1 as well. The off-by-one moves from parameter to column and back.
The payoff is performance and safety at once. The SQL text is fixed before any value exists, and the value arrives at bind time as a parameter, so it cannot rewrite the statement. That is the whole of the SQL injection lesson in one sentence: parameterize, never splice.
A placeholder is the boundary between code and data. setString(1, "JP") can never turn into a different query; string concatenation can, and does.
ResultSet: a cursor you move one row at a time
A ResultSet is not a collection. It is a cursor over rows, and it starts BEFORE the first row, so next() is the gate: it moves the cursor and returns true when there is a row to read. Every read after a false next() is meaningless, and running out of rows is not an error: false is the normal end of data.
Columns are read by label (getString("name")) or by 1-based index, and the getters convert SQL types to Java types. The conversions worth internalizing are the money and time ones: SQL DECIMAL arrives as BigDecimal because double cannot represent decimal fractions exactly, and DATE or TIMESTAMP columns map to java.time types through getObject with the target class (JDBC 4.2).
For large values, stream instead of materializing: getBinaryStream and getCharacterStream exist so a BLOB does not have to fit in your heap. And remember that null and 0 are different questions on a numeric column, which is what wasNull() answers.
| SQL type | Read it as | Note |
|---|---|---|
| INTEGER | getInt / getLong | a primitive getter returns 0 for NULL; check wasNull() if that distinction matters |
| DECIMAL(p, s) | getBigDecimal | exact decimal arithmetic; never double for money |
| VARCHAR, TEXT | getString | the driver handles decoding; your charset problems usually start at the connection |
| DATE | getObject(col, LocalDate.class) | the JDBC 4.2 mapping; no legacy java.sql.Date conversion step |
| TIMESTAMP | getObject(col, LocalDateTime.class) | TIMESTAMP WITH TIME ZONE maps to OffsetDateTime; some drivers also accept Instant |
| BLOB, CLOB | getBinaryStream / getCharacterStream | stream large values rather than materializing getBytes |
| NULL | any getter, then wasNull() | object getters simply return null |
One query · connection to cursor
Client
DriverManager.getConnection(url, "app", "secret")
Server
authentication, session created
ResultSet
no cursor yet
Open: DriverManager.getConnection asks the driver to establish a physical connection. TCP, authentication and session setup are included in the price, which is why pools exist.
Batches, generated keys and guardrails
A loop that executes the same INSERT a thousand times pays a network round trip a thousand times. addBatch collects the bound parameter sets and executeBatch sends them together, which is usually the biggest JDBC performance win available without changing the design.
- executeBatch: returns an array of per-statement counts. Failure behaviour is driver-specific, because some drivers reject the whole batch while others continue and report a negative value for the failed entry, so read the returned counts instead of assuming success.
- RETURN_GENERATED_KEYS: when you need the identity value the database assigned, pass the flag at prepare time and read it from
getGeneratedKeys()after the insert. - fetchSize: a hint for how many rows the driver pulls per network fetch. It is driver-specific in practice: on PostgreSQL it only takes effect with auto-commit off.
- Guardrails:
setMaxRowscaps the rows the client keeps, andsetQueryTimeoutstops a runaway query at the driver. Both limit damage; neither is tuning.
Batching removes round trips, generated keys retrieve identity. Both are still plain JDBC, and the frameworks in the next lessons dress exactly these calls.
Metadata, errors, and what sits on top
Two metadata objects let code discover instead of assume. DatabaseMetaData answers capability questions about the database, such as which identifier quote it uses or whether it supports batch updates; ResultSetMetaData describes a result you just received, with its column count, labels and types. Generic tooling is built on these two.
Errors arrive as SQLException, and it is a chain: getNextException() walks the list when the driver reports several failures at once. Every exception carries a five-character SQLState from the standard's classes (class 23 is an integrity constraint violation) plus a vendor-specific error code, and the SQLTransientException family marks failures that may succeed if you retry.
Everything above this layer, JPA, jOOQ, Spring JDBC, ends up calling the same Connection, PreparedStatement and ResultSet. Learn the objects and the frameworks become readable, and their leaks start making sense.
Frameworks hide the boilerplate, not the model: a connection is still a session, a statement is still a round trip, and a result set is still a cursor.
The connection you forget to close is still open on the server
A Connection is a session on the database server, and the server counts sessions against a hard limit. Leak one per request and the failure arrives from the other side: new requests cannot connect, while your JVM is using almost no memory. try-with-resources, reverse order, no exceptions.
Interview angles
Is Class.forName("org.postgresql.Driver") still required?+
No. Since JDBC 4, drivers register through the ServiceLoader by reading META-INF/services/java.sql.Driver, so the call is a relic. Keeping it is harmless but misleading: it suggests manual loading is needed, which has not been true for over a decade.
Statement or PreparedStatement?+
PreparedStatement for anything with a parameter or anything that runs more than once: the SQL text is fixed once, values bind as data, and many drivers reuse the server-side plan. Statement is for SQL you fully control and run once, such as DDL.
Common misconception: PreparedStatement is often described as simply faster. Plan reuse is driver and server dependent; the guarantee that holds everywhere is that parameters cannot change the shape of the query.
DriverManager or DataSource?+
DataSource in application code. It centralizes configuration, returns connections from a pool, and lets tests substitute behaviour. DriverManager.getConnection usually opens a fresh physical connection per call, which is fine in a script and ruinous in a request path.
Where does a ResultSet cursor start, and what does next() tell you?+
Before the first row. next() moves it one row forward and returns false when the result is exhausted, which is the normal exit of the loop rather than an error. Reading columns without a next() that returned true is a bug, not a null.
How do you read a DATE column into java.time?+
getObject(column, LocalDate.class), through the JDBC 4.2 mapping added in Java 8. TIMESTAMP maps to LocalDateTime and TIMESTAMP WITH TIME ZONE to OffsetDateTime; the legacy java.sql.Date and Timestamp classes are for old code and driver internals.
Why executeBatch, and what do the returned counts mean?+
It removes a round trip per statement by sending the bound parameter sets together. The returned int[] holds one count per statement, but failure behaviour is driver-specific: some reject the whole batch, some report a negative value per failure. Read the counts.