我有一个 try catch block ,如下所示。我正在尝试将其转换为 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);
}
最佳答案
将它们分成两个try-with-resources
:
try (
Connection connection = getConnection();
PreparedStatement preparedItemsStatement = connection.prepareStatement(myQuery);
) {
preparedItemsStatement.setString(1, userId + "%");
try (ResultSet rs = preparedItemsStatement.executeQuery()) {
...
try
block 中的语句必须是声明类型为 AutoCloseable
的变量的语句。
关于java - 使用 Try With 资源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37182281/