2016-05-12 9 views
1

Ich habe einen Versuch catch Block wie unten. Ich versuche, es in eine Try-with-resource umzuwandeln. Aber ich bin nicht in der Lage, dies zu tun, weil ich nicht normal Aussagen schreiben kann in neueren tryVerwendung von Try With Resource

 Connection connection = null; 
     PreparedStatement preparedItemsStatement = null; 
     ResultSet rs = null; 
     String id = null; 
     try { 
      connection = getConnection(); 
      preparedItemsStatement = connection.prepareStatement(myQuery); 
      preparedItemsStatement.setString(1, userId + "%"); 
      rs = preparedItemsStatement.executeQuery(); 
      if (rs != null && rs.next()) 
       id = rs.getString("SOME_ID"); 
     } catch (SQLException e) { 
      throw new SQLException("Error running Database query ", e); 
     } finally { 
      try { 
       if (rs != null) 
        rs.close(); 
       if (preparedItemsStatement != null) 
        preparedItemsStatement.close(); 
       if (connection != null) 
        connection.close(); 
      } catch (SQLException e) { 
       throw new SQLException("Error running Database query ", e); 
      } 
     } 

Was habe ich versucht,

  try (
       Connection connection = getConnection(); 
       PreparedStatement preparedItemsStatement = connection.prepareStatement(myQuery);     
       preparedItemsStatement.setString(1, userId + "%"); 
       ResultSet rs = preparedItemsStatement.executeQuery();     
      ) {   

      if (rs != null && rs.next()) 
       id = rs.getString("SOME_ID"); 
     } catch (SQLException e) { 
      throw new SQLException("Error running Database query ", e); 
     } 

Antwort

5

sie in zwei try-with-resources:

try (
    Connection connection = getConnection(); 
    PreparedStatement preparedItemsStatement = connection.prepareStatement(myQuery); 
    ) { 
     preparedItemsStatement.setString(1, userId + "%"); 
     try (ResultSet rs = preparedItemsStatement.executeQuery()) { 
      ... 

Die Anweisungen innerhalb des Blocks try müssen Anweisungen sein, die Variablen vom Typ deklarieren.

2

Sie können etwas tun:

try (Connection connection = getConnection();) {   
    try(PreparedStatement preparedItemsStatement = connection.prepareStatement(myQuery);){ 
     preparedItemsStatement.setString(1, userId + "%"); 
     try(ResultSet rs = preparedItemsStatement.executeQuery();){ 
      if (rs != null && rs.next()){ 
       id = rs.getString("SOME_ID"); 
      } 
     } 
    } 
} catch (SQLException e) { 
    throw new SQLException("Error running Database query ", e); 
} 

Beachten Sie, dass die Ressource, die Sie auf diese Weise geöffnet haben wird, sobald die Ausführung beendet, dass try Block geschlossen werden.

Verwandte Themen