It seems that the ResultSet
will be automatically closed when I close the Connection
.
But I want to return the ResultSet
and use it in another method, then I don't know where to close Connection
and PreparedStatement
.
public ResultSet executeQuery(String sql, String[] getValue)
{
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try
{
conn = getConn();
pstmt = conn.prepareStatement(sql);
if (getValue != null)
{
for (int i = 0; i < getValue.length; i++)
{
pstmt.setString(i + 1, getValue[i]);
}
}
rs = pstmt.executeQuery();
} catch (Exception e)
{
e.printStackTrace();
closeAll(conn, pstmt, rs);
}
return rs;
}
I've moved closeAll(conn, pstmt, null);
into catch block because I found that if I put it in finally block I'll lost my rs
immediately just before it returns.
Now when I want to close the rs
, I can't close the conn
and pstmt
. Is there any solution?
You really shouldn't handle with JDBC at the lower level. Use a framework like spring instead, it will handle all required
close()
operations for you.You can't use
ResultSet
after you've closedConnection
and/orPreparedStatement
. So, you need to pass an object on which to make a callback into this method.All cleanup should be done in
finally
blocks.Rewrite it like this
The cleaner way is to use CachedRowSetImpl. But on MySQL 5.x+ there are some bugs with selecting columns by name or label.
For use with MySQL use this version: https://stackoverflow.com/a/17399059/1978096
I'd recommend that you do something more like this: