gpt4 book ai didi

java - Findbugs错误 "Load of known null value"SQL连接

转载 作者:太空宇宙 更新时间:2023-11-04 12:34:10 25 4
gpt4 key购买 nike

我有 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;
}
}

但是有问题。 Finbugs 给我一个错误,说:

在 DAO.getRole 中加载已知空值

may fail to clean up java.sql.Statement

那么我应该怎样做才能避免这种情况呢?

最佳答案

getRole 可以返回 null。此外:

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

我更喜欢另一种表示法。不幸的是,错误解决方案包括让 getRole 抛出异常(最好)或让返回 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(); //
}

关于java - Findbugs错误 "Load of known null value"SQL连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37520076/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com