簡體   English   中英

JDBC 連接嘗試與資源使用

[英]JDBC connection try with resources use

我是 Java 編程新手,對嘗試使用資源共享代碼有疑問

String statement= "<statement>";
DataSource ds = createDSConnection();
if (ds == null) return;

try (PreparedStatement prepare = ds.getConnection().prepareStatement(statement)) {
    // statement values
    prepare.execute();
} catch (Exception e) {
}

這會關閉 PrepareStatement 和 db.connection(),還是僅關閉 PreparedStatement?

您顯示的代碼只會關閉准備好的語句,並泄漏連接。 如果要同時關閉兩者,則需要在資源塊中為每個資源使用一條語句:

try (Connection connection = ds.getConnection();
     PreparedStatement prepare = connection.prepareStatement(statement)) {
    // your code here
}

暫無
暫無

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

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