簡體   English   中英

使用JDBC資源的正確方法

[英]The correct way to use JDBC 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 它足夠安全嗎?

資源是必須在程序完成后關閉的對象。因此,您不必在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);
    } 

您應該始終釋放/關閉您使用的資源,例如ResultSet,Statement,Connection。 那應該在finally塊中完成。 您在此處粘貼的代碼段看起來還可以(只要在QuietDb中關閉了s和c)。

雖然關閉Connection將關閉與之關聯的所有Statement ,但是在大多數數據庫中,對於一個Connection可以同時打開多少Statement ,存在一個上限。

如果不關閉Statement ,則會增加出現ORA-01000: maximum open cursors exceeded類的錯誤的可能性ORA-01000: maximum open cursors exceeded

如果關閉Statements它們也將關閉其ResultSet ,因此您不必同時關閉兩者。

使用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);
}

這樣可以保證語句和連接都被關閉(即使關閉該語句也會引發Exception!)。 唯一的區別可能是關閉時可能會拋出異常,因為我不知道您的DbUtils.close吞下了異常。

通常,try-with-resources提供了更簡潔的代碼,並且可以更好地確保資源以正確的順序正確關閉,而無需花費太多時間。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM