1

我想用

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 中。但它说这不受支持。我能做些什么?

4

2 回答 2

5

这是 Java SE 7 中的新特性 try-with-resource。在 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 习语来分解重复位。

于 2012-08-11T17:54:09.167 回答
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来避免样板代码。

于 2012-08-11T17:57:58.243 回答