您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

声纳:“关闭此PreparedStatement”

声纳:“关闭此PreparedStatement”

我已经按照@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;
}
其他 2022/1/1 18:29:18 有517人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶