Why is 声纳Qube http://docs.sonarqube.org/如果我在finally块中关闭它,Jenkins的插件会抱怨打开的语句?
(我需要在单独的函数中验证数据库连接。)
final String PING = "SELECT 1 from dual";
public boolean validateConnection(Connection conn) {
PreparedStatement statement = null;
try{
if(conn == null){
LOGGER.log( LogEntries.PingError, "Null connection on PING. Reached max # of connections or network issue. Stats: "+getCacheStatistics() );
return false;
}
if(conn.isClosed()){
// logger
return false;
}
statement = conn.prepareStatement( PING ); //%%%%%% SONAR: Close this "PreparedStatement".
statement.setQueryTimeout(QUERY_TIMEOUT);
try( ResultSet rs = statement.executeQuery() ){
if ( rs != null && rs.next() ) {
return true;
}
}catch(Exception exRs){
// logger
throw exRs;
}
}catch(Exception ex){
// logger
}finally{
try{
statement.close();
}catch(Exception excpt){
// logger
}
}
return false;
}
我已经按照 @TT 和声纳的建议以这种方式重构了我的代码停止抱怨.
public boolean validateConnection(Connection conn) {
LOGGER.log( LogEntries.PingConn );
try{
if(conn == null){
LOGGER.log( LogEntries.PingError, "Null connection on PING. Reached max # of connections or network issue. Stats: "+getCacheStatistics() );
return false;
}
if(conn.isClosed()){
LOGGER.log( LogEntries.PingError, "Found closed connection during validation PING." );
return false;
}
try( PreparedStatement statement = conn.prepareStatement( PING ) ){
statement.setQueryTimeout(QUERY_TIMEOUT);
try( ResultSet rs = statement.executeQuery() ){
if ( rs != null && rs.next() ) {
return true;
}
}
}
}catch(Exception ex){
LOGGER.log( LogEntries.PingError, ex );
}
return false;
}
如果没有“try-with-resource”,代码可以通过以下方式重构,但在本例中为 Sonar仍然抱怨:
public boolean validateConnection(Connection conn) {
LOGGER.log( LogEntries.PingConn );
PreparedStatement statement = null;
ResultSet rs = null;
try{
if(conn == null){
LOGGER.log( LogEntries.PingError, "Null connection on PING. Reached max # of connections or network issue. Stats: "+getCacheStatistics() );
return false;
}
if(conn.isClosed()){
LOGGER.log( LogEntries.PingError, "Found closed connection during validation PING." );
return false;
}
statement = conn.prepareStatement( PING );
statement.setQueryTimeout( QUERY_TIMEOUT );
rs = statement.executeQuery();
if ( rs != null && rs.next() ) {
return true;
}
}catch(Exception ex){
LOGGER.log( LogEntries.PingError, ex );
}finally{
try {
if(rs!=null){
rs.close();
}
} catch (SQLException eClosing1) {
LOGGER.log( LogEntries.PingError, eClosing1 );
}finally{
try {
if(statement!=null){
statement.close();
}
}catch (SQLException eClosing2) {
LOGGER.log( LogEntries.PingError, eClosing2 );
}
}
}
return false;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)