2016-05-12 68 views
1

我有如下一个try catch块。我正试图将其转换为Try-with-resource。但我不能这样做,因为我不会写在新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

其拆分成两个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块封闭。