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
  • 54,493
  • 18
  • 133
  • 262
Ersin Gülbahar
  • 6,713
  • 15
  • 60
  • 114

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
  • 143,103
  • 30
  • 210
  • 299
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
  • 20,718
  • 8
  • 67
  • 109