java 成员对象 丢失_java-JDBC:如果丢失对Connection对象的引用,连...

…will the connection terminate automatically once the method returns?

不,不会.它最终可能会关闭,也可能不会最终关闭,但是如果有的话,距离它还需要很长的时间.如果连接类的终结器处于打开状态,则它可能会关闭该连接,但是在很多情况下,终结器永远不会运行.显式调用con.close()至关重要.

这是我通常的处理方式(尽管我已经将很多这种逻辑考虑进了助手中,因为否则很冗长):

public static void C()

throws SQLException

{

Connection con = DriverManager.getConnection();

try {

.... // code

// done with the connection

con.close();

con = null;

}

finally {

if (con != null) {

try {

con.close();

}

catch (Exception e) {

// Eat it to avoid masking any exception that

// got us here

}

}

}

}

请注意,在finally子句中检测到未关闭的连接后,我将其关闭,但不允许任何异常,否则可能会导致抛出该错误.这是因为主逻辑正确地关闭了连接,这意味着,如果我在finally块中找到了打开的连接,则已经引发了异常,我们正在处理它,所以我不想掩饰它.与con.close()引发不同的异常.

有了体面的助手,它就会变得更短,更容易编写:

public static void C()

throws SQLException

{

Connection con = DriverManager.getConnection();

try {

.... // code

// done with the connection

con = JDBCHelper.close(con); // <== This one *allows* any exception that occurs

}

finally {

con = JDBCHelper.quietClose(con); // <== This one *eats* any exception that occurs

}

}

…其中JDBCHelper(假设类)包含:

public static final Connection close(Connection con)

throws SQLException

{

con.close();

return null;

}

public static final Connection quietClose(Connection con)

{

if (con != null) {

try {

con.close();

}

catch (Exception e) {

}

}

return null;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值