私は以下のように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);
}