You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在含return语句的方法中关闭Connection与Statement?

如何关闭方法中的Connection与Statement资源?

你的当前方法存在两个明显问题:一是未关闭数据库连接(con)、Statement(st)和ResultSet(rs),会导致数据库资源泄漏;二是通过字符串拼接SQL语句存在SQL注入风险,建议改用PreparedStatement替代Statement。

下面提供两种可靠的资源关闭方案,优先推荐第二种:


方案1:使用try-finally手动关闭(兼容Java 6及以下)

需要在finally块中依次关闭资源,注意关闭顺序:先关ResultSet,再关Statement,最后关Connection,且每个关闭操作都要单独包裹try-catch,避免因某一个资源关闭失败导致后续资源无法关闭。

public static int howManyPassengersInCabin(int i) throws SQLException {
    Connection con = null;
    Statement st = null;
    ResultSet rs = null;
    try {
        con = connectionForDB();
        String query = "SELECT Capacity FROM cabin WHERE Cabin_ID = " + i;
        st = con.createStatement();
        rs = st.executeQuery(query);
        rs.next();
        return rs.getInt("Capacity");
    } finally {
        // 关闭ResultSet
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                // 可记录日志,或直接忽略(避免掩盖原有异常)
            }
        }
        // 关闭Statement
        if (st != null) {
            try {
                st.close();
            } catch (SQLException e) {
                // 可记录日志,或直接忽略
            }
        }
        // 关闭Connection
        if (con != null) {
            try {
                con.close();
            } catch (SQLException e) {
                // 可记录日志,或直接忽略
            }
        }
    }
}

方案2:使用try-with-resources自动关闭(Java 7+ 推荐)

Java 7及以上支持try-with-resources语法,所有实现AutoCloseable接口的资源(Connection、Statement、ResultSet都实现了)会在代码块结束后自动关闭,无需手动写finally,代码更简洁安全,同时建议改用PreparedStatement避免SQL注入:

public static int howManyPassengersInCabin(int i) throws SQLException {
    // try块中声明资源,自动关闭
    try (Connection con = connectionForDB();
         PreparedStatement pst = con.prepareStatement("SELECT Capacity FROM cabin WHERE Cabin_ID = ?")) {
        pst.setInt(1, i); // 设置参数,避免SQL注入
        try (ResultSet rs = pst.executeQuery()) {
            rs.next();
            return rs.getInt("Capacity");
        }
    }
}

说明:

  • try-with-resources会按资源声明的逆序自动关闭,即先关ResultSet,再关PreparedStatement,最后关Connection
  • 使用PreparedStatement通过占位符?设置参数,彻底避免SQL注入风险,这是数据库操作的最佳实践

内容的提问来源于stack exchange,提问作者chanuka vidanapathirana

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 06:06:24