Quick revision
The short answer
We borrow a Connection from the DataSource, prepare select id, total from orders where customer_id = ?, bind the customer id with setLong, and read the rows in a while (rs.next()) loop. The Connection, PreparedStatement and ResultSet must all be closed, and try-with-resources closes them in reverse order even when an exception is thrown. With a pool, closing the Connection returns it to the pool rather than closing the socket, and any SQLException carries a SQLState and a vendor error code that tell us what went wrong.
What to remember
In this answer, we wrote a plain JDBC method that borrows a connection, prepares a parameterised query, binds the customer id with setLong and reads each row in a while (rs.next()) loop. We saw that the Connection, PreparedStatement and ResultSet all hold resources and that try-with-resources closes them in reverse order even when an exception is thrown, that closing a pooled connection returns it to the pool instead of closing the socket, and that SQLState and vendor codes are how we diagnose a failure.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
We borrow a Connection from the DataSource, prepare select id, total from orders where customer_id = ?, bind the customer id with setLong, and read the rows in a while (rs.next()) loop. The Connection, PreparedStatement and ResultSet must all be closed, and try-with-resources closes them in reverse order even when an exception is thrown. With a pool, closing the Connection returns it to the pool rather than closing the socket, and any SQLException carries a SQLState and a vendor error code that tell us what went wrong.
Why this question is asked
Most of us use JdbcTemplate, JPA or jOOQ, but every one of them does these same steps underneath, and when something leaks or fails in production, the explanation is at this level. Interviewers ask for plain JDBC to check that we know which objects hold resources, how to close them safely, and how to read a failure. In this answer, we will recap the objects involved, write the method, see why try-with-resources is the right way to close them, look at what closing means for a pooled connection, and read a SQLException properly.
1A Quick Recap of the JDBC Objects
JDBC is the standard Java API for relational databases. A DataSource is a factory for connections; in a Spring Boot application it is usually a HikariCP pool. A Connection is a session with the database, backed by a network socket. A PreparedStatement is a SQL statement with placeholders, the question marks, whose values we set separately; the driver sends the values apart from the SQL text, which also protects us from SQL injection. A ResultSet is a cursor over the rows a query returns, positioned before the first row until we call next().
All three hold resources. The connection holds a socket and, in a pool, a slot that other threads may be waiting for. The statement can hold memory and server-side resources such as a prepared statement handle. The result set can hold buffered rows or an open cursor on the server. So each must be closed when we are done, in the reverse order of opening.
2Writing the Method
Here is the method with a small record for the result. Each resource is declared in a try-with-resources header, so Java closes it automatically.
Notice a few details. Parameter indexes start at 1, not 0. We read columns by name, which survives a change in column order; reading by index, rs.getLong(1), is slightly faster but more fragile. We use getBigDecimal for money, because a double cannot represent values like 59.90 exactly. The ResultSet has its own try block because it is created after we set the parameter, but it could also live in the outer header if no setup were needed between.
3Why try-with-resources Closes Things Correctly
Before Java 7 we wrote nested finally blocks, each with its own null check and try-catch around close(). It was easy to get wrong: an exception from one close() could skip the next one and leak the connection. try-with-resources fixes that. Every object declared in the header must implement AutoCloseable, and Java guarantees that each one is closed when the block ends, normally or by an exception, in the reverse order of declaration.
- Borrow a Connection
dataSource.getConnection(), may wait for the pool - Prepare the statementSQL with ? placeholders
- Bind the parameters
ps.setLong(1, customerId) - Execute and iteratewhile (
rs.next()) read each row - Close ResultSet, then PreparedStatementreverse order, automatic
- Close the Connectionreturns it to the pool
6 steps in order. Play them, or step through them one at a time.
try-with-resources runs the last two steps even if any earlier step throws.
So the main error reaches the caller, and nothing leaks on the way. JDBC also says that closing a Statement closes its ResultSet, and closing a Connection should release its statements, but relying on that cascade is risky with pools, because a pooled connection's close() does not really close the physical connection. Closing each object explicitly, as try-with-resources does, is the safe habit.
4What Closing a Pooled Connection Means
With HikariCP, dataSource.getConnection() does not open a socket. It hands us a proxy around a physical connection the pool already opened. When we call close() on that proxy, the pool rolls back any uncommitted work, resets settings such as auto-commit and read-only to their defaults, closes any statements we left open, and marks the physical connection as free for the next caller. The socket to the database stays open, which is the whole point of the pool.
That is why forgetting to close a pooled connection is so harmful. The physical connection stays marked as in use forever, and after the pool's maximum, ten by default in HikariCP, every later call to getConnection() waits up to connectionTimeout, 30 seconds by default, and then fails.
5Reading a SQLException
When something goes wrong, the driver throws SQLException. Its message is meant for humans, but two fields are meant for code. getSQLState() returns a five-character code from the SQL standard: the first two characters are the class, so 23 means an integrity constraint violation and 08 means a connection problem. getErrorCode() returns the vendor's own number, which is specific to each database. getNextException() may hold further errors, which matters for batches.
Notice that PostgreSQL relies mostly on SQLState, while MySQL also fills the vendor code, so portable code checks the SQLState class first. Spring's JdbcTemplate uses exactly these two fields to translate SQLException into its own exception hierarchy, such as DuplicateKeyException for a unique violation, which saves us writing this mapping ourselves.
6Follow-up questions
What happens if you forget to close a pooled connection?
The pool still counts it as borrowed, so it is never reused; the physical connection stays open on the database too. Each leak shrinks the usable pool by one, and once every connection has leaked, all callers block in getConnection() until connectionTimeout expires and then fail with a message such as Connection is not available, request timed out after 30000ms. HikariCP's leakDetectionThreshold setting logs the stack trace of the code that borrowed a connection and held it longer than the threshold, which usually points straight at the missing close.
Should we close the ResultSet explicitly if we close the statement?
Closing the statement is specified to close its current result set, so in simple code it is enough. But explicit closing in try-with-resources costs nothing, releases the result set's memory or server cursor as early as possible, and protects us from drivers or pool wrappers that behave differently. It is the habit worth keeping.
Why use PreparedStatement instead of building the SQL string?
Because the value travels separately from the SQL text, the database never interprets it as SQL, which prevents SQL injection. It also lets the driver and database reuse the parsed statement across executions, and it handles types such as dates and decimals correctly without us formatting them into strings.
7Conclusion
In this answer, we wrote a plain JDBC method that borrows a connection, prepares a parameterised query, binds the customer id with setLong and reads each row in a while (rs.next()) loop. We saw that the Connection, PreparedStatement and ResultSet all hold resources and that try-with-resources closes them in reverse order even when an exception is thrown, that closing a pooled connection returns it to the pool instead of closing the socket, and that SQLState and vendor codes are how we diagnose a failure.
Open with
I would get a Connection from the DataSource, prepare the statement select id, total from orders where customer_id = ?, bind the customer id with ps.setLong(1, customerId), execute it, and loop with while (rs.next()), reading the id with getLong and the total with getBigDecimal, ideally by column name, into a list of small records.
Then, if they want more
The important part is closing. The Connection, the PreparedStatement and the ResultSet all hold resources: a pool slot and a socket, a statement handle, and buffered rows or a server cursor. I declare them in try-with-resources, so Java closes them automatically in reverse order, result set first, then statement, then connection, and it does that even when the query throws.
If a close also throws, that exception is added as suppressed, so the original error still reaches the caller. With a pool like HikariCP, closing the connection does not close the socket; the pool rolls back anything uncommitted, resets the connection's settings and marks it free for the next caller.
That is why forgetting to close it is serious: the pool thinks it is still in use, and once all ten default connections leak, every caller waits thirty seconds and fails. Leak detection in HikariCP logs where the connection was borrowed.
Finally, when something fails I look at the SQLException's SQLState, the standard five-character code where the class tells me the kind of failure, and the vendor error code, plus any chained exceptions.
About this answer
- Last updated
- 12 November 2026
- Versions it names
- Java 7
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- java.sql, package documentation
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "Write plain JDBC code that reads all orders for a customer using a DataSource, and...": https://scrivio-interview-library.netlify.app/databases/jdbc/cb877c752e/