Try-With-Resources with JDBC
Fast recall
Quick revision
Core answer
Connection, Statement/PreparedStatement, and ResultSet implement AutoCloseable, so try-with-resources closes successfully opened objects in reverse order. Closing a pooled Connection normally returns it to the pool rather than physically closing the database session. PreparedStatement bind parameters protect data values from SQL injection when used correctly, but SQL identifiers and dynamically built clauses need separate safe handling.Whether you can apply try-with-resources to the real JDBC trio and know why leaking connections is catastrophic
Closing only the Connection (not Statement/ResultSet), or building queries with string concatenation instead of PreparedStatement
Explain that leaked connections exhaust the pool and take the whole service down, and that PreparedStatement also prevents value-based SQL injection when placeholders are used correctly
Interview-ready guide
Interview answer
JDBC resources implement AutoCloseable, so I declare the connection, prepared statement, and result set in dependency order and let try-with-resources close them in reverse. Successfully opened resources also close if a later initializer or the query fails.
For a pooled connection, close normally returns the logical connection to the pool instead of tearing down the physical session. That is essential because leaked connections can consume the pool's configured capacity. I use PreparedStatement placeholders for untrusted data values. They do not parameterize table or column names, so dynamic SQL structure requires a separate allow-list or safe builder.
Try-With-Resources with JDBC
Direct Answer
JDBC Connection, Statement/PreparedStatement, and ResultSet implement AutoCloseable, so try-with-resources closes successfully opened objects in reverse order. Closing a pooled Connection normally returns it to the pool rather than physically closing the database session. PreparedStatement bind parameters protect data values from SQL injection when used correctly, but SQL identifiers and dynamically built clauses need separate safe handling.
Common Mistakes & Pitfalls
- Closing only the
Connection. TheStatementandResultSetleak too — declare all three. - String-concatenating SQL. Use
PreparedStatementwith?parameters to stop SQL injection. - Leaking on the error path. Manual code that closes only on success still leaks when a query throws.
- Holding the connection too long. Open late, close early; don't span unrelated work.
Check your understanding
Answer these without looking back at the article.
- What happens if you forget to close a JDBC connection in a try-finally?
- Why does ResultSet need to be in a separate inner try-with-resources?
- How does Spring's JdbcTemplate handle connection management internally?
Looking for a structured roadmap?
Every module on this page is also part of the full Java backend interview track.