使用SonarCloud
我收到了这个 bug :
Use try-with-resources or close this "ResultSet" in a "finally" clause
这是以下代码:
public long executeUpdate() throws SQLException {
if (query != null) {
try {
statement.execute();
if (returnGeneratedKeys) {
ResultSet resultSet = statement.getGeneratedKeys();
if (resultSet.next()) {
return resultSet.getLong(1);
}
}
} finally {
statement.close();
connection.close();
}
}
return 0;
}
答案 0 :(得分:1)
您可以这样做:
public long executeUpdate() throws SQLException {
if (query != null) {
try {
statement.execute();
if (returnGeneratedKeys) {
try (ResultSet resultSet = statement.getGeneratedKeys()) {
if (resultSet.next()) {
return resultSet.getLong(1);
}
}
}
} finally {
statement.close();
connection.close();
}
}
return 0;
}
以下结构:
try (ResultSet resultSet = statement.getGeneratedKeys()) {
if (resultSet.next()) {
return resultSet.getLong(1);
}
}
等于:
ResultSet resultSet = statement.getGeneratedKeys()
try {
if (resultSet.next()) {
return resultSet.getLong(1);
}
} finally {
if (resultSet != null) {
resultSet.close()
}
}