30

I have a website which is getting a massive number of hits. I'm experienced problems, including JDBC connection errors.

I'm a bit confused about closing PreparedStatement. Do I need to close PreparedStatement or is it just enough to only close Statement?

Also, what about ResultSet? Do I need to close it too?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
user836026
  • 10,608
  • 15
  • 73
  • 129
  • 5
    What does the documentation say? –  Jan 27 '13 at 10:48
  • 2
    Posible Duplicate of [Closing Database Connections in Java](http://stackoverflow.com/questions/2225221/closing-database-connections-in-java) – Paul Vargas Jan 27 '13 at 10:49
  • 1
    Show your statement here about which you are asking – Abhishekkumar Jan 27 '13 at 10:49
  • 2
    As [the official tutorial closes PreparedStatements](http://docs.oracle.com/javase/tutorial/jdbc/basics/prepared.html) it's safe to assume you have to close them I guess.. – fvu Jan 27 '13 at 10:49
  • 2
    Are you talking about closing the `Statement` or `Connection`? Why shall closing an `Statement` handle closing a non-related `PreparedStatement`? – Amir Pashazadeh Jan 27 '13 at 11:03
  • 1
    See also [Must JDBC Resultsets and Statements be closed separately although the Connection is closed afterwards?](https://stackoverflow.com/questions/4507440/must-jdbc-resultsets-and-statements-be-closed-separately-although-the-connection) – Vadzim Mar 12 '18 at 20:21

2 Answers2

27

Yes, you have to close the prepared statements (PreparedStatement Object) and result sets as they may cause memory leakage.

For more information, see Using Prepared Statements.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
prasanth
  • 3,502
  • 4
  • 28
  • 42
  • 2
    No, it is enough to close the `Connection` only, which closes all `Statements` and `PreparedStatements` created from it, and `ResultSets` created in turn from them, but if you're using a lot of `PreparedStatements` and `ResultSets` *per connection* it would be *wise* to close them as soon as possible. There is nothing in your link that supports your claim. – user207421 Feb 25 '20 at 04:06
7

Yes, you must close it. If the connection from a pool, closing it actually sends it back to the pool for reuse.

Close in the finally{} block, such that if an exception is thrown, you still get the chance to close this.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Ravindra Bagale
  • 17,226
  • 9
  • 43
  • 70