Which should I close first, the PreparedStatement or the Connection?

froadie picture froadie · Mar 2, 2010 · Viewed 27k times · Source

When using a PreparedStatement in JDBC, should I close the PreparedStatement first or the Connection first? I just saw a code sample in which the Connection is closed first, but it seems to me more logical to close the PreparedStatement first.

Is there a standard, accepted way to do this? Does it matter? Does closing the Connection also cause the PreparedStatement to be closed, since the PreparedStatement is directly related to the Connection object?

Answer

Brian Agnew picture Brian Agnew · Mar 2, 2010

The statement. I would expect you to close (in order)

  1. the result set
  2. the statement
  3. the connection

(and check for nulls along the way!)

i.e. close in reverse order to the opening sequence.

If you use Spring JdbcTemplate (or similar) then that will look after this for you. Alternatively you can use Apache Commons DbUtils and DbUtils.close() or DbUtils.closeQuietly().