相关疑难解决方法(0)

虽然Connection之后关闭,但必须单独关闭JDBC结果集和语句吗?

据说在使用后关闭所有JDBC资源是一个好习惯.但是,如果我有以下代码,是否有必要关闭Resultset和Statement?

Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try {
    conn = // Retrieve connection
    stmt = conn.prepareStatement(// Some SQL);
    rs = stmt.executeQuery();
} catch(Exception e) {
    // Error Handling
} finally {
    try { if (rs != null) rs.close(); } catch (Exception e) {};
    try { if (stmt != null) stmt.close(); } catch (Exception e) {};
    try { if (conn != null) conn.close(); } catch (Exception e) {};
}
Run Code Online (Sandbox Code Playgroud)

问题是连接的关闭是否完成了工作,或者是否使用了一些资源.

java jdbc

245
推荐指数
6
解决办法
18万
查看次数

尝试/尝试使用资源和Connection,Statement和ResultSet关闭

我最近和我的教授讨论了如何处理基本的jdbc连接方案.假设我们想要执行两个查询,这就是他的建议

public void doQueries() throws MyException{
    Connection con = null;
    try {
        con = DriverManager.getConnection(dataSource);
        PreparedStatement s1 = con.prepareStatement(updateSqlQuery);
        PreparedStatement s2 = con.prepareStatement(selectSqlQuery);

        // Set the parameters of the PreparedStatements and maybe do other things

        s1.executeUpdate();
        ResultSet rs = s2.executeQuery();

        rs.close();
        s2.close();
        s1.close();
    } catch (SQLException e) {
        throw new MyException(e);
    } finally {
        try {
            if (con != null) {
                con.close();
            }
        } catch (SQLException e2) {
            // Can't really do anything
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我不喜欢这种方法,我有两个问题:

1.A),我认为,如果有异常,我们做"其他的事情",或者在该行抛出rs.close()还是 …

java correctness try-with-resources

13
推荐指数
3
解决办法
2万
查看次数

标签 统计

java ×2

correctness ×1

jdbc ×1

try-with-resources ×1