2012-08-11 27 views
1

我想用JDK 6不支持Statement和ResultSet。我可以用什麼來代替這些?

import java.sql.ResultSet; 
import java.sql.SQLException; 
import java.sql.Statement; 

. 
. 
. 


try (Statement stmt = connection.createStatement()) { 

       try (ResultSet rset = stmt.executeQuery(url)) { 
        while (rset.next()) { 
        System.out.println (rset.getString(1)); 
         } 
       } 
      } 

在JDK 6,但它說,這是不支持的。我能做什麼?

+0

這是真正的代碼片段嗎?它不會編譯。你能否也發佈進口報表? – SiB 2012-08-11 16:02:03

+0

我不認爲它是Statement或ResultSet,它是try/catch塊。嘗試catch( e){} – ksnortum 2012-08-11 16:04:32

+0

我編輯問題。 – 2012-08-11 16:06:41

回答

5

這是嘗試與 - 資源是在Java SE 7在Java SE 6中的新功能(最近有一個壽命延長到明年,但我不會爲它編寫新代碼):

Statement stmt = connection.createStatement() { 
try { 
    ResultSet rset = stmt.executeQuery(url) 
    try { 
     while (rset.next()) { 
      System.out.println (rset.getString(1)); 
     } 
    } finally { 
     rset.close(); 
    } 
} finally { 
    stmt.close(); 
} 

您可以使用Execute Around idiom來分解重複位。

1

Try-with-resources是Java 7中引入的功能。您需要手動管理您的資源。

Statement stmt = null; 
ResultSet rset = null; 
try { 
    stmt = connection.createStatement(); 
    rset = stmt.executeQuery(url); 
    while (rset.next()) { 
     System.out.println(rset.getString(1)); 
    } 
} catch (Exception e) { 
    // In your real code catch expecific exceptions and do something about it. 
} finally { 
    if (rset != null) { 
     try { 
      rset.close(); 
     } catch (Exception e) {} // Same thing 
    } 
    if (stmt != null) { 
     try { 
      stmt.close(); 
     } catch (Exception e) {} // Same thing 
    } 
} 

可選地使用諸如Apache dbutils或更好Spring Framework JDBC庫來避免樣板代碼。

相關問題