关闭

示例代码:如何正确close从连接池中取得的db连接

1150人阅读 评论(0) 收藏 举报
Here is an example of properly written code to use a db connection obtained from a connection pool:
  Connection conn = null;
  Statement stmt = null;  // Or PreparedStatement if needed
  ResultSet rs = null;
  try {
    conn = ... get connection from connection pool ...
    stmt = conn.createStatement("select ...");
    rs = stmt.executeQuery();
    ... iterate through the result set ...
    rs.close();
    rs = null;
    stmt.close();
    stmt = null;
    conn.close(); // Return to connection pool
    conn = null;  // Make sure we don't close it twice
  } catch (SQLException e) {
    ... deal with errors ...
  } finally {
    // Always make sure result sets and statements are closed,
    // and the connection is returned to the pool
    if (rs != null) {
      try { rs.close(); } catch (SQLException e) { ; }
      rs = null;
    }
    if (stmt != null) {
      try { stmt.close(); } catch (SQLException e) { ; }
      stmt = null;
    }
    if (conn != null) {
      try { conn.close(); } catch (SQLException e) { ; }
      conn = null;
    }
  }
 
摘自:

The Apache Jakarta Tomcat 5 Servlet/JSP Container

JNDI Datasource HOW-TO

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:175607次
    • 积分:2920
    • 等级:
    • 排名:第12547名
    • 原创:96篇
    • 转载:19篇
    • 译文:12篇
    • 评论:3条