使用JDBC资源的正确方法

时间:2014-04-17 16:07:44

标签: java jdbc try-with-resources

我经常在Java 7中看到类似的代码

    Connection c = null;
    PreparedStatement s = null;
    try {
        c = dataSource.getConnection();

        String sql = "insert into table (column1, column2) values (?, ?);
        s = c.prepareStatement(sql);
        int i = 1;
        s.setString(i++, "111");
        s.setString(i++, "222");

        s.execute();

    } catch (SQLException e) {
        log.error("failed to insert", e);
    } finally {
        DbUtils.close(s, c); // closes s and c with no questions
    }

但是根据规范,当连接关闭时,所有语句和结果集都被释放。

我听说JDBC驱动程序有可能不遵守JDBC API的规则,旧方法更好。我的问题是听取有关这方面的意见。代码看起来更好但是如果它很危险怎么办? 在我看来,最喜欢的方法是在这里使用 try-with-resources 。它足够安全吗?

4 个答案:

答案 0 :(得分:1)

资源是在程序完成后必须关闭的对象。因此,您不必在finally块中手动关闭对象

 String sql = "insert into table (column1, column2) values (?, ?);
    try(Connection  c = dataSource.getConnection();
    PreparedStatement s = c.prepareStatement(sql);) {


        int i = 1;
        s.setString(i++, "111");
        s.setString(i++, "222");

        s.execute();

    } catch (SQLException e) {
        log.error("Failed to insert transaction", e);
    } 

答案 1 :(得分:0)

您应该始终释放/关闭您使用的资源,如ResultSet,Statement,Connection。那应该在finally块中完成。您在此处粘贴的代码段看起来没问题(就S和C在QuietDb中关闭而言)。

答案 2 :(得分:0)

closing a Connection will close all Statements associated with it期间,大多数数据库都有一个上限,即您可以为任何一个Statement同时打开ConnectionStatement

如果您不关闭ORA-01000: maximum open cursors exceeded,则会增加Statements等错误的可能性。

如果您关闭{{1}},they also close their ResultSets,那么您就不必关闭它们。

答案 3 :(得分:0)

使用try-with-resources您的代码可以重写为:

try (
    Connection c = dataSource.getConnection();
    PreparedStatement s = c.prepareStatement("insert into table (column1, column2) values (?, ?)");
) {
    int i = 1;
    s.setString(i++, "111");
    s.setString(i++, "222");

    s.execute();
} catch (SQLException e) {
    log.error("failed to insert", e);
}

这可以保证语句和连接都被关闭(即使关闭语句也会抛出异常!)。唯一的区别可能是关闭时可能会抛出异常,因为我不知道你的DbUtils.close是否会吞下异常。

通常,try-with-resources提供更清晰的代码,更确保资源以正确的顺序正确关闭,而不需要太多锅炉板。

相关问题