簡體   English   中英

Findbugs錯誤“加載已知空值”SQL連接

[英]Findbugs error “Load of known null value” SQL connection

我有DAO類,有獲取和發送數據的方法。

我正在捕獲SQL請求中的異常,因此我需要在try括號之外聲明連接變量。

每個方法看起來都像這樣:

public Role getRole(int roleId) {
    Connection connection = null;
    ResultSet rs = null;
    PreparedStatement statement = null;
    Role role = null;

    try {
        connection = dataSource.getConnection();
        statement = connection.prepareStatement("select ROLE_ID, ROLE_TEXT from ROLES WHERE ROLE_ID = :1");
        statement.setInt(1, roleId);
        rs = statement.executeQuery();
        rs.next();
        role = roleMapper.mapRow(rs, 1);
    } catch (SQLException e) {
    } finally {
        JdbcUtils.closeResultSet(rs);
        JdbcUtils.closeStatement(statement);
        JdbcUtils.closeConnection(connection);
        return role;
    }
}

但是有問題。 蠢貨給我一個錯誤,說:

Load of known null value in DAO.getRole

may fail to clean up java.sql.Statement

那么我應該怎么做才能避免這種情況呢?

getRole可以返回null。 此外:

if (rs.next()) {
    role = roleMapper.mapRow(rs, 1);
}

我更喜歡另一種符號。 不幸的是,錯誤解決方案包括讓getRole拋出異常(最好)或讓return返回Optional<Role>

//public Role getRole(int roleId) throws SQLException {
public Optional<Role> getRole(int roleId) {
    try (Connection connection = dataSource.getConnection();
            PreparedStatement statement =
                connection.prepareStatement(
                "select ROLE_ID, ROLE_TEXT from ROLES WHERE ROLE_ID = :1")) {
        statement.setInt(1, roleId);
        try (ResultSet rs = statement.executeQuery()) {
            if (rs.next()) {
                return roleMapper.mapRow(rs, 1);
            }
        }
    } catch (SQLException e) { //
        Logger.getLogger(getClass().getName()).log(Level.SEVERE, "ID: " + roleId, e); //
    }
    return Optional.empty(); //
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM