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
本文提供了一个使用连接池获取数据库连接的正确示例代码。该示例展示了如何创建Statement、执行查询并正确关闭资源,确保连接能够返回到连接池中重复使用。
941

被折叠的 条评论
为什么被折叠?



