开发者

Is there a method of doing close from the outside of the method of generating Statement and ResultSet generated from Connection?

开发者 https://www.devze.com 2023-03-22 12:59 出处:网络
I am Japanese. English is unskill开发者_运维技巧ed. I\'m sorry. Is there a method of doing close from the outside of the method of generating Statement and ResultSet generated from Connection?

I am Japanese. English is unskill开发者_运维技巧ed. I'm sorry. Is there a method of doing close from the outside of the method of generating Statement and ResultSet generated from Connection?

However, I want to close() it these one without calling Connection#close(). I learn the instance of Connection from the outside of the method.


No. JDBC requires you to close all these objects by yourself (and in finally blocks to be able to handle exceptions).

Closing just the connection should close all objects derived from it, but I would not depend on that, and it is better to close those as soon as possible anyway. The opposite is certainly not true (closing a ResultSet will not close the connection), and there is also no way to get the parent Connection from a ResultSet (which I think was the gist of your question).

I would suggest to not use JDBC directly, but a more friendly framework on top, at least something as minimal like Commons DBUtils, which takes care of cleaning up these resources.


When ever you open any connection or creating any Statement/ResultSet explicitly close them. Always try to call this method after you done with your JDBC code

public  void closeResultSetAndStatement(final Connection connection,
            final Statement statement, final ResultSet resultSet) {
        try {
            if (null != resultSet) {
                resultSet.close();
            }
        } catch (Exception e) {
            Log.warn(
                    "Exception while resultset statement. Not Throwing Exception, Ignoring it.",
                    e);
        }

        try {
            if (null != statement) {
                statement.close();
            }
        } catch (Exception e) {
            Log.warn(
                    "Exception while closing statement. Not Throwing Exception, Ignoring it.",
                    e);
        }

        try {
                    if (null != connection) {
            connection.close();
                     } 
        } catch (Exception e) {
            Log.warn(
                    "Connection could not be closed. Not Throwing Exception, Ignoring it.",
                    e);
        }
    }
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号