Is it safe to do connection.createStatement().executeQuery(String query);
, or should each java.sql.Statement
object be created and closed by "hand" on every use, even if the connection is closed in a finally block?
If multiple queries are executed in one method by one connection it would use much less code if instantiating and closing each statement wasn't strictly necess开发者_如何学JAVAary.
It's true that closing a Connection
in almost all JDBC driver implementations also implicitly closes the Statement
. But, a big but, when you're using a connection pool (and you would like to use one because that greatly improves connecting performance), the close()
will not close the Connection
, but release it back to the pool, hereby leaving the Statement
open. And when you do this too often, you will run out of resources sooner or later which may kill your application.
Always acquire and close all the three resources Connection
, Statement
and ResultSet
in the shortest possible scope, no excuses.
Move all the boilerplate code to a helper method/class.
That way you can acquire/release resource in the manner consistent with JDBC (or any other limited resource package) documentation and yet have your business logic not be polluted by JDBC clutter.
And though it may seem like a waste to you now, but there is nothing wrong with dedicating single query to a single method in your business logic class.
精彩评论