资源泄漏:' ps'可能不会在这个位置关闭

时间:2015-09-01 16:30:27

标签: java jdbc

看看这个简单的数据库查询方法,它在返回行中给我警告Resource Leak: 'ps' may not be closed at this location

public Bancos getDefault() {
    Debug.out("");

    PreparedStatement ps = null;
    Bancos banco = null;

    try {

        String query = "SELECT * FROM " + TABLE_BANCOS + " " +
                       "WHERE " + FIELD_KEY + " = ?;";

        ps = connector.prepareStatement(query);
        ps.setString(1, new ParametrosManager().getParametros().getCodigoBanco());

        ResultSet rs = ps.executeQuery();
        if(rs.next()) {
            banco = new Bancos(
                    rs.getString(FIELD_KEY),
                    rs.getDate(FIELD_DATAREGISTO),
                    rs.getString(FIELD_ABREVIATURA),
        }

        rs.close();
        ps.close();

    } catch(SQLException se) {
        se.printStackTrace();
    } finally {
        try {
            if(ps != null) 
                ps.close();
        } catch(SQLException se) {
            se.printStackTrace();
        }
    }

    return banco;
}

我想知道为什么 eclipse 给了我这个警告,因为我甚至在ps块上关闭了finally。这只是一个误报吗?

我使用Java 7。

解决方案:

Java 7似乎存在问题,请从重复的问题中查看answer

所以,固定代码:

public Bancos getDefault() {
    Debug.out("");

    Bancos banco = null;
    String query = "SELECT * FROM " + TABLE_BANCOS + " " +
                   "WHERE " + FIELD_KEY + " = ?;";

    try( PreparedStatement ps = connector.prepareStatement(query); ) {
        ps.setString(1, new ParametrosManager().getParametros().getCodigoBanco());

        ResultSet rs = ps.executeQuery();
        if(rs.next()) {
            banco = new Bancos(
                    rs.getString(FIELD_KEY),
                    rs.getDate(FIELD_DATAREGISTO),
                    rs.getString(FIELD_ABREVIATURA),
        }

        rs.close();

    } catch(SQLException se) {
        se.printStackTrace();
    }

    return banco;
}

感谢Luiggi指出我的答案。

1 个答案:

答案 0 :(得分:2)

您认为此警告是误报是正确的。

在Eclipse 4.5中测试代码我没有收到任何警告。似乎Eclipse Java编译器中的静态分析在此期间得到了改进。