Java Findbugs错误“;“已知空值的加载”;SQL连接
我有一个DAO类,其中包含获取和发送数据的方法 我正在捕捉SQL请求中的异常,所以我需要在try括号之外声明连接变量 每个方法看起来都是这样的:Java Findbugs错误“;“已知空值的加载”;SQL连接,java,sql,jdbc,findbugs,Java,Sql,Jdbc,Findbugs,我有一个DAO类,其中包含获取和发送数据的方法 我正在捕捉SQL请求中的异常,所以我需要在try括号之外声明连接变量 每个方法看起来都是这样的: public Role getRole(int roleId) { Connection connection = null; ResultSet rs = null; PreparedStatement statement = null; Role role = null; try { con
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;
}
}
但有个问题。Finbug给了我一个错误,说:
加载DAO.getRole中的已知空值
及
那么我应该做些什么来避免这种情况呢?getRole可以返回null。 此外:
if (rs.next()) {
role = roleMapper.mapRow(rs, 1);
}
我喜欢另一种符号。不幸的是,错误解决方案包括要么让getRole抛出异常(最佳),要么让getRole返回一个可选的
//公共角色getRole(int-roleId)引发SQLException{
公共可选getRole(int-roleId){
try(Connection=dataSource.getConnection();
准备好的报表=
连接。准备陈述(
“从角色中选择角色\u ID,角色\u文本,其中角色\u ID=:1”)){
声明.setInt(1,roleId);
try(ResultSet rs=statement.executeQuery()){
如果(rs.next()){
返回roleMapper.mapRow(rs,1);
}
}
}捕获(SQLE){//
Logger.getLogger(getClass().getName()).log(Level.SEVERE,“ID:”+roleId,e)//
}
返回可选的.empty()//
}
getRole可以返回null。
此外:
if (rs.next()) {
role = roleMapper.mapRow(rs, 1);
}
我更喜欢另一种表示法。不幸的是,错误解决方案要么让getRole抛出异常(最佳),要么让getRole返回一个可选的
//公共角色getRole(int-roleId)引发SQLException{
公共可选getRole(int-roleId){
try(Connection=dataSource.getConnection();
准备好的报表=
连接。准备陈述(
“从角色中选择角色\u ID,角色\u文本,其中角色\u ID=:1”)){
声明.setInt(1,roleId);
try(ResultSet rs=statement.executeQuery()){
如果(rs.next()){
返回roleMapper.mapRow(rs,1);
}
}
}捕获(SQLE){//
Logger.getLogger(getClass().getName()).log(Level.SEVERE,“ID:”+roleId,e)//
}
返回可选的.empty()//
}
永远不要捕获未处理的异常在哪一行出现错误?请发布整个错误消息我的解决方案是使用try with resources:正如Jens所说,不要捕获并忽略异常。也不要假设查询返回了什么,检查rs.next的结果。
永远不要捕获未处理的异常在wh你收到错误了吗?请发布整个错误消息。我的解决方案是使用try with resources:正如Jens所说,不要捕获并忽略异常。也不要假设查询返回了什么,检查rs.next
的结果。
//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(); //
}