2013-06-20 105 views
0

下面的代碼工作正常:爲什麼在這種情況下不能使用try-with-resource?

String connStr = "jdbc:mysql://localhost:3306/addressbook"; 

try (Connection conn = DriverManager.getConnection(connStr, "root", ""); 
    PreparedStatement ps = conn.prepareStatement("select * from contact where firstName=?"); 
     ) { 

    ps.setString(1, "Cippo"); 
    ResultSet rs = ps.executeQuery(); 

    while(rs.next()) { 
     System.out.print(rs.getString(2) + "\t"); 
     System.out.print(rs.getString(3) + "\t"); 
     System.out.print(rs.getInt(1) + "\t"); 
     System.out.print(rs.getString(4) + "\t"); 
     System.out.println(rs.getString(5));      
    } 

} catch (SQLException e) { 
    e.printStackTrace(); 
    System.exit(-1); 
} 

但是當我移動其他兩個指令進入試與 - 資源塊(其中他們應該留)一個神祕的原因,我得到一個編譯錯誤:

String connStr = "jdbc:mysql://localhost:3306/addressbook"; 

try (Connection conn = DriverManager.getConnection(connStr, "root", ""); 
    PreparedStatement ps = conn.prepareStatement("select * from contact where firstName=?"); 
     ps.setString(1, "Cippo"); 
     ResultSet rs = ps.executeQuery(); 
     ) { 

    while(rs.next()) { 
     System.out.print(rs.getString(2) + "\t"); 
     System.out.print(rs.getString(3) + "\t"); 
     System.out.print(rs.getInt(1) + "\t"); 
     System.out.print(rs.getString(4) + "\t"); 
     System.out.println(rs.getString(5));      
    } 

} catch (SQLException e) { 
    e.printStackTrace(); 
    System.exit(-1); 
} 

編譯錯誤是不合理的:「ps無法解析」。但康恩解決沒有任何問題。爲什麼?

+1

我認爲除了'try(...)'部分中的賦值操作外,我不能做任何事情,但我不確定。所以你的codenipet:'ps.setString(1,「Cippo」)'是在一個無效的地方。 – Quirin

回答

0

try with resources語法用於分配實現autocloseable的對象,例如流和數據庫連接,以便在發生異常時可以正確清理它們。它不是爲執行任意附加代碼而設計的。

因爲您已經在第一個示例中獲得了相同的結果,所以將這兩條指令放在try語句的分配部分中,我確實沒有看到您想要實現的目標。

更新:我不知道你是否將ResultSet放在嘗試中,以便它在失敗時自動關閉。如果是這種情況,那麼我認爲它應該通過調用關閉聲明對象自動關閉。如果你擔心一個單獨的內部嘗試與ResultSet資源就足夠了。

0

這就是Java語法是如何定義的:

Java Language Specification, Section 14.20.3 try-with-resources

A try-with-resources statement is parameterized with variables (known as resources) that are initialized before execution of the try block and closed automatically, in the reverse order from which they were initialized, after execution of the try block. [...]

A ResourceSpecification declares one or more local variables with initializer expressions to act as resources for the try statement.

相關問題