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