2016-05-12 7 views
1

私は以下のようにtry catchブロックを持っています。私はそれをTry-with-resourceに変換しようとしています。リソースを試してみる

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

:しかし、私は新しいtry私が試した何

 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

は2 try-with-resourcesにそれらを分割し、そうすることができませんでしよ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ブロックを出るときに閉鎖されることに注意してください。

関連する問題