Where to close a JDBC Connection while I want to return the ResultSet
Actually, you've almost answered that question yourself. As you experimented, closing the Connection
will release the JDBC resources associated to it (at least, this is how things should work). So, if you want to return a ResultSet
(I'll come back on this later), you need to close the connection "later". One way to do this would be obviously to pass a connection to your method, something like this:
public ResultSet executeQuery(Connection conn, String sql, String[] getValue);
The problem is that I don't really know what is your final goal and why you need so low level stuff so I'm not sure this is a good advice. Unless if you are writing a low level JDBC framework (and please, don't tell me you are not doing this), I would actually not recommend returning a ResultSet
. For example, if you want to feed some business class, return some JDBC-independent object or a collection of them as other have advised instead of a ResultSet
. Also bear in mind that a RowSet
is a ResultSet
so if you should not use a ResultSet
then you should not use a RowSet
.
Personally, I think you should use some helper class instead of reinventing the wheel. While Spring may be overkill and has a bit of learning curve (too much if you don't know it at all), Spring is not the only way to go and I strongly suggest to look at Commons DbUtils. More specifically, look at QueryRunner
and especially this query()
method:
public <T> T query(String sql,
ResultSetHandler<T> rsh,
Object... params)
throws SQLException
As you can see, this method allows to pass a ResultSetHandler
which exposes a callback method to convert ResultSets
into other objects as described in z5h's answer and DbUtils provides several implementations, just pick up the one that will suit your needs. Also have a look at the utility methods of the DbUtils
class, for example the various DbUnit.close()
that you may find handy to close JDBC resources.
Really, unless you have very good reasons to do so (and I'd be curious to know them), don't write yet another JDBC framework, use an existing solution, it will save you some pain and, more important, some bugs and you'll benefit from proven good design. Even for low level stuff, there are existing (and simple) solutions as we saw. At least, check it out.