栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

声纳:“关闭此PreparedStatement”

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

声纳:“关闭此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;}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/451678.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号