2016-05-12 2 views
1

У меня есть блок catch try, как показано ниже. Я пытаюсь преобразовать его в Try-with-resource. Но я не в состоянии сделать это, потому что я не могу писать нормальные операторы в новой tryИспользование 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); 
      } 
     } 

То, что я пробовал,

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

ответ

5

разделить их на две try-with-resources:

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

Операторы внутри блока try должны быть операторами, объявляющими переменные типа AutoCloseable.

2

Вы можете сделать что-то вроде этого:

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

Имейте в виду, что ресурс, который вы открыли этот путь будет закрыт, как только исполнение выходит, что try блок.

Смежные вопросы