Closing JDBC Connections — try-with-resources
Fast recall
Quick revision
Core answer
Whether you close connections correctly and reach for try-with-resources instead of a manual finally block.
Closing only in the happy path, or only inside the try body, so an early exception skips close() and leaks the connection.
Note that try-with-resources closes in reverse declaration order and that on a pool, close() returns the connection rather than destroying it.
Interview-ready guide
Interview answer
try (Connection c = dataSource.getConnection();
PreparedStatement ps = c.prepareStatement(SQL)) {
ps.setLong(1, id);
try (ResultSet rs = ps.executeQuery()) {
while (rs.next()) { /* map row */ }
}
}If mapping throws, ResultSet, statement, and connection still close. In a Hikari pool the final close returns the handle for reuse. A vendor's basic DataSource may close the underlying database connection instead.
Closing JDBC Connections — try-with-resources
Direct Answer
Use try-with-resources for Connection, PreparedStatement, and ResultSet so each closes even when work fails. With a pooling DataSource, Connection.close normally returns the logical connection to the pool; with a non-pooled connection it normally closes the physical session. DataSource itself does not guarantee pooling. Resources close in reverse declaration/nesting order.
Common Mistakes & Pitfalls
Closing only in the happy path, or only inside the try body, so an early exception skips close() and leaks the connection.
Check your understanding
Answer these without looking back at the article.
- What is the format of a JDBC connection URL?
- What is a JDBC connection pool and why is it important?
- What information is needed to create a JDBC connection?
Looking for a structured roadmap?
Every module on this page is also part of the full Java backend interview track.