检查 Java ResultSet 中的 null int 值

新手上路,请多包涵

在 Java 中,我试图从 ResultSet 测试空值,其中列被转换为原始 int 类型。

 int iVal;
ResultSet rs = magicallyAppearingStmt.executeQuery(query);
if (rs.next()) {
  if (rs.getObject("ID_PARENT") != null && !rs.wasNull()) {
    iVal = rs.getInt("ID_PARENT");
  }
}

从上面的代码片段来看,有没有更好的方法来做到这一点,我假设第二个 wasNull() 测试是多余的?

教育我们,谢谢

原文由 ian_scho 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 657
2 个回答

The default for ResultSet.getInt when the field value is NULL is to return 0 , which is also the default value for your iVal declaration.在这种情况下,您的测试是完全多余的。

如果您真的想在字段值为 NULL 时做一些不同的事情,我建议:

 int iVal = 0;
ResultSet rs = magicallyAppearingStmt.executeQuery(query);
if (rs.next()) {
    iVal = rs.getInt("ID_PARENT");
    if (rs.wasNull()) {
        // handle NULL field value
    }
}

(编辑为下面的@martin 评论;所写的 OP 代码无法编译,因为 iVal 未初始化)

原文由 Richard 发布,翻译遵循 CC BY-SA 3.0 许可协议

另一个解决方案:

 public class DaoTools {
    static public Integer getInteger(ResultSet rs, String strColName) throws SQLException {
        int nValue = rs.getInt(strColName);
        return rs.wasNull() ? null : nValue;
    }
}

原文由 Patrice IMBERT 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题