试用/试用资源和连接,语句和结果集关闭tl;博士使用资源试用语法代码示例更新: Java 9
我最近和我的教授讨论了如何处理基本的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
        }
    }
}
我不喜欢这种方法,我有两个问题:
1.A)我认为,如果在我们做“其他事情”的地方抛出任何异常,或者在行中,或者在方法结束时不会被关闭。我说的对吗?rs.close()s2.close()s1
1.B)教授一直要求我明确关闭ResultSet(即使声明文档明确表示它将关闭ResultSet),她说Sun推荐它。有什么理由这样做吗?
现在,我认为这是同一事物的正确代码:
public void doQueries() throws MyException{
    Connection con = null;
    PreparedStatement s1 = null;
    PreparedStatement s2 = null;
    try {
        con = DriverManager.getConnection(dataSource);
        s1 = con.prepareStatement(updateSqlQuery);
        s2 = con.prepareStatement(selectSqlQuery);
        // Set the parameters of the PreparedStatements and maybe do other things
        s1.executeUpdate();
        ResultSet rs = s2.executeQuery();
    } catch (SQLException e) {
        throw new MyException(e);
    } finally {
        try {
            if (s2 != null) {
                s2.close();
            }
        } catch (SQLException e3) {
            // Can't do nothing
        }
        try {
            if (s1 != null) {
                s1.close();
            }
        } catch (SQLException e3) {
            // Can't do nothing
        }
        try {
            if (con != null) {
                con.close();
            }
        } catch (SQLException e2) {
            // Can't do nothing
        }
    }
}
2.A) 这个代码是否正确?(是否保证在方法结束时所有内容都将关闭?
2.B)这是非常大和冗长的(如果有更多的语句,情况会变得更糟)有没有更短或更优雅的方法来做到这一点,而不使用尝试资源?
最后,这是我最喜欢的代码
public void doQueries() throws MyException{
    try (Connection 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();
    } catch (SQLException e) {
        throw new MyException(e);
    }
}
3) 此代码是否正确?我认为我的教授不喜欢这种方式,因为没有明确关闭ResultSet,但她告诉我,只要在文档中很明显所有内容都已关闭,她就可以接受它。你能用类似的例子给出任何指向官方文档的链接,或者基于文档显示此代码没有问题吗?