从 Java ResultSet 检查空 int 值 [英] Checking for a null int value from a Java ResultSet

查看:17
本文介绍了从 Java ResultSet 检查空 int 值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Java 中,我试图从 ResultSet 中测试空值,其中将列强制转换为原始 int 类型.

In Java I'm trying to test for a null value, from a ResultSet, where the column is being cast to a primitive int type.

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

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

From the code fragment above, is there a better way to do this, and I assume that the second wasNull() test is redundant?

教育我们,谢谢

推荐答案

ResultSet.getInt 字段值为 NULL 时默认返回 0,这也是 iVal 声明的默认值.在这种情况下,您的测试完全是多余的.

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. In which case your test is completely redundant.

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

If you actually want to do something different if the field value is NULL, I suggest:

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 未初始化)

(Edited as @martin comments below; the OP code as written would not compile because iVal is not initialised)

这篇关于从 Java ResultSet 检查空 int 值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆