A few months back I learned that when working with java.sql.connection I needed to close PreparedStatements and ResultSet to prevent memory leakage, as explained here
However I recently started working with a new team that uses org.sql2o.connection which is a nice and useful jdbc wrapper, but I noticed that they don't usually close their org.sql2o.Query objects.
try(org.sql2o.Connection c = Sql2oObject.open()){
//...some logic
List<SomeClass> list = c.createQuery(sql).executeAndFetch(SomeClass.class);
//...some more logic
}
As you can see the query object is never explicitly closed. I think that it would be better to close the query as well as such:
try(org.sql2o.Connection c = sql2oObject.open();
org.sql2o.Query q = c.createQuery(sql); ) {
//...some logic
List<SomeClass> list = q.executeAndFetch(SomeClass.class);
//...some more logic
}
But I'm not sure if it is really necessary. If it is, then I've found a major probable leak and I will be regarded as a genius and remembered throughout the eternity. If is not, then I'm just a guy asking for an unnecessary change.
So, what do you say oh mighty SO? is it necessary to close them?
Not really you have to call close as the way you have used the
sql2o.connectionas you are using it with try-with-resource approach in Java.What it does in try-with-resource java is compiler adds the
finallystatement for your code where you suppose to close the native resource explicitly. Otherwise you must close thesql2o.connectioninside a finally block. Since its a jdbc wrapper around the standardjdbc connectionIf you want to close other underline resources as well with try-with-resource declare them all in the parenthesis. So that it will close underline resources together with your main resource. However in your case
Querydoes not needs to be closed explicitly since its always part of thesql2o.connection