---
title: "关于ResultSet的关闭问题"
author: "vencent"
date: "2006-03-15T15:15:00Z"
tags: []
slug: "resultset"
draft: false
lastmod: "2006-03-15T15:15:00Z"
id: 48797
url: "https://vencent.iteye.com/blog/48797"
---

**在Connection上调用close方法会关闭Statement和ResultSet吗？**

级联的关闭这听起来好像很有道理，而且在很多地方这样做也是正确的，通常这样写  
Connection con = getConnection();//getConnection is your method  
PreparedStatement ps = con.prepareStatement(sql);  
ResultSet rs = ps.executeQuery();  
……  
///rs.close();  
///ps.close();  
con.close();  // NO!  
这 样做的问题在于Connection是个接口，它的close实现可能是多种多样的。在普通情况下，你用 DriverManager.getConnection()得到一个Connection实例，调用它的close方法会关闭Statement和 ResultSet。但是在很多时候，你需要使用数据库连接池，**在连接池中的得到的Connection上调用close方法的时候，Connection可能并没有被释放，而是回到了连接池中。**它以后可能被其它代码取出来用。如果没有释放Statement和ResultSet，那么在Connection上没有关闭的Statement和ResultSet可能会越来越多，那么……  
相反，我看到过这样的说法，有人把Connection关闭了，却继续使用ResultSet，认为这样是可以的，引发了激烈的讨论，到底是怎么回事就不用我多说了吧。

所以我们必须很小心的释放数据库资源，下面的代码片断展示了这个过程

Connection con = null;  
PreparedStatement ps = null;  
ResultSet rs = null;

try {  
    con = getConnection();//getConnection is your method  
    ps = con.prepareStatement(sql);  
    rs = ps.executeQuery();  
    ///...........  
}  
catch (SQLException ex) {  
    ///错误处理  
}  
finally{  
    try {  
        if(ps!=null)  
            ps.close();  
    }  
    catch (SQLException ex) {  
        ///错误处理  
    }  
    try{  
        if(con!=null)  
            con.close();  
    }  
    catch (SQLException ex) {  
        ///错误处理  
    }  
}

很麻烦是不是？但为了写出健壮的程序，这些处理是必须的。

上面这东西讲得真是精辟。  
![](http://www.blogjava.net/Vencent/aggbug/35497.html)

[Vencent Chen](http://www.blogjava.net/Vencent/) 2006-03-15 23:15 [发表评论](http://www.blogjava.net/Vencent/archive/2006/03/15/35497.html#Feedback)