有关连接池的疑惑。

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;
}
}

以上例子引自:http://jakarta.apache.org/tomcat/tomcat-5.0-doc/jndi-datasource-examples-howto.htmlDatabase%20Connection%20Pool%20(DBCP)%20Configurations

我的问题是: conn.close(); // Return to connection pool 这一句,这个connection已经关闭了,怎么会返回连接池呢?

谢谢!

Connection是interface,如果你使用的是weblogic应用服务器的话,该connect是weblogic.jdbc.wrapper实例,你可以看看JTSConnection类的代码
protected void doClose(){
......
if(cc.isPooled())
{
closeAllStatements(true);
ConnectionPoolManager.release(cc); //如果采用连接池的话,ConnectionPoolManager会把连接释放到pool中
} else
{
closeAllStatements(true);
cc.destroy();
}
...
}


只是数据库连接池的一种处理方式,为的是让使用连接池和不使用的程序没有什么区别,实际情况是你在做关闭的时候,会被一个类似钩子的东西把真正的关闭程序构住,转而执行连接释放操作。

请查看proxy类,基础类库中