代码如下:
Connection connection = null;
try {
connection = createConnection();
String sql = String.format(STRING_FOR_PROCEDURE, name);
connection.createStatement().execute(sql);
connection.commit();
} catch (Exception e) {
throw new DatabaseServiceException(e.getMessage(), e);
} finally {
closeConnection(connection);
}
我想sonar希望我在“finally”块中用这样的方法来关闭连接:
connection.close();
但我对此使用自定义方法,即:
protected void closeConnection(Connection connection) {
try {
if (connection != null) {
connection.close();
}
} catch (SQLException ex) {
LOGGER.log(Level.SEVERE, null, ex);
}
}
此方法需要在当前类中使用。 但是我收到了sonar blocker“使用try-with-resources或者在”finally“子句中关闭这个语句”。 有办法解决它吗?
注意,您的错误是“use try-with-resources or close this statement in a”finally“子句。”
问题不在于如何关闭连接。 问题是你没有结束你的陈述。
Connection connection = null;
Statement statement = null;
try {
connection = createConnection();
String sql = String.format(STRING_FOR_PROCEDURE, name);
statement = connection.createStatement();
statement.execute(sql);
connection.commit();
} catch (Exception e) {
throw new DatabaseServiceException(e.getMessage(), e);
} finally {
if (statement != null) {
try {
statement.close();
} catch (SQLException e) {
Logger.log(Level.SEVERE, "Could not close Statement.", e);
}
}
closeConnection(connection);
}
请记住,在关闭连接之前需要关闭语句。
声纳有助于设计正确的代码,但有时如果你很清楚,我们可以忽略警告。 但是是的,你能做到吗?
Connection connection = null;
try {
connection = createConnection();
String sql = String.format(STRING_FOR_PROCEDURE, name);
connection.createStatement().execute(sql);
connection.commit();
} catch (Exception e) {
throw new DatabaseServiceException(e.getMessage(), e);
} finally {
try {
if (connection != null) {
connection.close();
}
} catch (SQLException ex) {
LOGGER.log(Level.SEVERE, null, ex);
}
}