正确关闭数据库连接至关重要,应优先使用 try-with-resources 语句自动关闭 Connection、PreparedStatement 和 ResultSet,避免资源泄漏;若用传统方式,需在 finally 中按 ResultSet → Statement → Connection 顺序手动关闭并捕获异常;使用连接池时 close() 是归还连接而非断开,仍需调用。

在 Java 中操作数据库时,正确关闭数据库连接非常重要,否则可能导致连接泄漏、资源耗尽或系统性能下降。标准做法是确保 Connection、Statement(或 PreparedStatement)和 ResultSet 都被正确关闭,推荐使用 try-with-resources 语句来自动管理资源。
使用 try-with-resources 自动关闭连接(推荐写法)
这是 Java 7 引入的最佳实践方式,所有实现了 AutoCloseable 接口的资源会在 try 块结束时自动关闭,无需手动调用 close(),也避免了因异常导致未关闭的问题。示例代码:
基于jsp+javabean+access(mysql)三层结构的动态购物网站,v1.2包含v1.0中未公开的数据库连接 的java源文件 一,网站前台功能: 产品二级分类展示:一级分类--二级分类--产品列表--详细介绍(名称,图片,市场价,会员价,是否推荐,功能介绍等) 产品搜索:关键字模糊搜索 定购产品:选择商品--确认定购--填写收货人信息--选择付款方式--订单号自动生成(限登录用户)
String url = "jdbc:mysql://localhost:3306/mydb";
String username = "root";
String password = "123456";
String sql = "SELECT id, name FROM users WHERE id = ?";
try (Connection conn = DriverManager.getConnection(url, username, password);
PreparedStatement pstmt = conn.prepareStatement(sql);
ResultSet rs = pstmt.executeQuery()) {
while (rs.next()) {
System.out.println("ID: " + rs.getInt("id") + ", Name: " + rs.getString("name"));
}
} catch (SQLException e) {
e.printStackTrace();
}
// Connection、PreparedStatement、ResultSet 已自动关闭
传统 try-catch-finally 手动关闭(旧版兼容写法)
在不支持 try-with-resources 的老项目中,必须在 finally 块中手动关闭资源,并按 ResultSet → Statement → Connection 的顺序关闭,且每个关闭操作都要包裹在 try-catch 中防止异常中断其他资源释放。示例代码:
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
conn = DriverManager.getConnection(url, username, password);
pstmt = conn.prepareStatement(sql);
rs = pstmt.executeQuery();
while (rs.next()) {
System.out.println("ID: " + rs.getInt("id") + ", Name: " + rs.getString("name"));
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try { if (rs != null) rs.close(); } catch (SQLException e) { e.printStackTrace(); }
try { if (pstmt != null) pstmt.close(); } catch (SQLException e) { e.printStackTrace(); }
try { if (conn != null) conn.close(); } catch (SQLException e) { e.printStackTrace(); }
}
关键注意事项
- 资源关闭顺序应为:ResultSet → Statement → Connection,反过来关闭可能引发异常。
- 即使发生 SQLException,也必须确保连接被关闭,否则连接会一直占用直到超时。
- 使用连接池(如 HikariCP、Druid)时,close() 并不会真正断开物理连接,而是将连接归还给连接池,因此仍需正常调用 close()。
- 不要重复调用 close(),可能会抛出异常或造成不可预期行为。










