使用Try With Resource

时间:2016-05-12 09:10:11

标签: java try-catch

我有一个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);
        }

2 个答案:

答案 0 :(得分:5)

将它们分成两个try-with-resources

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

try块中的语句必须是声明AutoCloseable类型变量的语句。

答案 1 :(得分:2)

您可以这样做:

public class StudioBundleListener implements BundleListener {
@Override
   public void bundleChanged(BundleEvent event) {
   String symbolicName = event.getBundle().getSymbolicName();
   int type = event.getType();
   if(symbolicName.equals(MYPlugin.PLUGIN_ID) && type == BundleEvent.STARTED) {
     //Register my listeners
   }
 }
}

请记住,只要执行退出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); } 阻止,您以这种方式打开的资源就会关闭。