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

查看:322
本文介绍了从Java ResultSet检查null 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检查null int值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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