1

I have to program a Web Crawler (uni assignment), thus I have to store/read/update lots of data to/from a MySQL Database.

I'm using JDBC connector and on every-time I call a method to contact the database I'm defining a PreparedStatement & ResultSet and finally i close the RS and finally the PS.

However I use the same methods so many times that instead of making the program more Time/Resource Efficient I'm making it slower/heavier (that's why I don't close the connection too). So the question is there any other reason to close those or should I let them open?

If I don't close them the program seems not to have any issue but I don't want it to seem correct but truly be.

Edit: Thanks for the ideas on how to close but the question is not How to but "Is it mandatory". Closing makes the program slow so I need to know if I cannot close (seems that it's bad practise) or at least find a better alternative.

nikoswsn
  • 192
  • 3
  • 11
  • please reaad this.. it will answer you questions.. http://stackoverflow.com/questions/2225221/closing-database-connections-in-java – RamPrakash Jan 09 '17 at 19:10

1 Answers1

3
  • It's always best practice to define PreparedStatement and ResultSet locally (i.e. in a method) and close them once the execution is done.

  • PreparedStatement acts as a cursor between your program and database, and if not closed, might result in maximum open cursors exceeded error (in case of Oracle) as number of cursors/descriptors that can be open are limited per connection.

  • As far as closing ResultSet is concerned, closing PreparedStatement automatically closes ResultSet (here is the javadoc). Ideally, you should be using try with resources block for implementation.

Darshan Mehta
  • 30,102
  • 11
  • 68
  • 102
  • 1
    I will test try-with-sources instead of finally-try-finally-try. Connection should close too or not? Maybe if that's needed I can restart the connection once in a while – nikoswsn Jan 09 '17 at 20:29