java mysql关闭连接,在Java中关闭数据库连接

I am getting a little confused, I was reading the below from http://en.wikipedia.org/wiki/Java_Database_Connectivity

Connection conn = DriverManager.getConnection(

"jdbc:somejdbcvendor:other data needed by some jdbc vendor",

"myLogin",

"myPassword" );

Statement stmt = conn.createStatement();

try {

stmt.executeUpdate( "INSERT INTO MyTable( name ) VALUES ( 'my name' ) " );

} finally {

//It's important to close the statement when you are done with it

stmt.close();

}

Do you not need to close the conn Connection?

What is really happening if the conn.close() doesn't occur?

I have a private web app I'm maintaining that doesn't currently close either form, but is the important one really the stmt one, the conn one, or both?

The site keeps going down intermittently but the server keeps saying it's a database connection issue, my suspicion is that it's not being closed, but I don't know which if any to close.

解决方案

When you are done with using your Connection, you need to explicitly close it by calling its close() method in order to release any other database resources (cursors, handles, etc) the connection may be holding on to.

Actually, the safe pattern in Java is to close your ResultSet, Statement, and Connection (in that order) in a finally block when you are done with them, something like that:

Connection conn = null;

PreparedStatement ps = null;

ResultSet rs = null;

try {

// Do stuff

...

} catch (SQLException ex) {

// Exception handling stuff

...

} finally {

if (rs != null) {

try {

rs.close();

} catch (SQLException e) { /* ignored */}

}

if (ps != null) {

try {

ps.close();

} catch (SQLException e) { /* ignored */}

}

if (conn != null) {

try {

conn.close();

} catch (SQLException e) { /* ignored */}

}

}

The finally block can be slightly improved into (to avoid the null check):

} finally {

try { rs.close(); } catch (Exception e) { /* ignored */ }

try { ps.close(); } catch (Exception e) { /* ignored */ }

try { conn.close(); } catch (Exception e) { /* ignored */ }

}

But, still, this is extremely verbose so you generally end up using an helper class to close the objects in null-safe helper methods and the finally block becomes something like that:

} finally {

DbUtils.closeQuietly(rs);

DbUtils.closeQuietly(ps);

DbUtils.closeQuietly(conn);

}

And, actually, the Apache Commons DbUtils has a DbUtils class which is precisely doing that so there is no need to write your own.

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值