在Java中关闭数据库连接的合适方法是什么? [英] What is the suitable way to close the database connection in Java?

查看:202
本文介绍了在Java中关闭数据库连接的合适方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图关闭数据库连接。但是有点混乱,比如说

I tried to close the DB connection.But had a bit of confusion, say

ResultSet rs = null 

我是否必须靠近

rs.close();

DatabaseUtil.closeResultSet(rs);

有什么区别?

推荐答案

这些方法只关闭 ResultSet 。您仍然必须关闭所有 Statement Connection 实例。我建议在 finally 块中这样做。类似的东西,

Those methods only close the ResultSet. You still have to close all Statement and Connection instances. I recommend doing so in a finally block. Something like,

Connection conn = null;
Statement stmt = null'
ResultSet rs = null;
try {
  conn = getConnection();
  stmt = conn.prepareStatement(sql);
  stmt.setString(1, "Hello"); 
  rs = stmt.executeQuery();
  while (rs.next()) {
    // ...
  }
} catch (SQLException se) {
  se.printStackTrace();
} finally {
  if (rs != null) {
    try {
      rs.close();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
  if (stmt != null) {
    try {
      stmt.close();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
  if (conn != null) {
    try {
      conn.close();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}

如果你使用我的 关闭实用程序 finally块可以是,

If you use my Close utility the finally block could be,

} finally {
  Close.close(rs, stmt, conn);
}

这篇关于在Java中关闭数据库连接的合适方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆