1

I want to use

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

in jdk 6. But it says that this is not supported. What can I do?

MvG
  • 57,380
  • 22
  • 148
  • 276
CompEng
  • 7,161
  • 16
  • 68
  • 122

2 Answers2

5

That's try-with-resource which is a new feature in Java SE 7. In Java SE 6 (recently had a life extension into next year, but I wouldn't write new code for it):

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();
}

You can use the Execute Around idiom to factor out to repetitive bits.

Community
  • 1
  • 1
Tom Hawtin - tackline
  • 145,806
  • 30
  • 211
  • 305
1

Try-with-resources is a feature introduced with Java 7. You need to manage your resources by hand.

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 
   }
}

Alternatively use a library such as Apache dbutils or better yet Spring Framework JDBC to avoid the boilerplate code.

Anthony Accioly
  • 21,918
  • 9
  • 70
  • 118