从 Java ResultSet 检查空 int 值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2920364/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 14:30:20  来源:igfitidea点击:

Checking for a null int value from a Java ResultSet

javanullresultset

提问by ian_scho

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

在 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");
  }
}

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

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

Educate us, and Thanks

教育我们,谢谢

采纳答案by Richard

The default for ResultSet.getIntwhen the field value is NULLis to return 0, which is also the default value for your iValdeclaration. In which case your test is completely redundant.

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

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

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

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

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

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

回答by Andreas Dolk

I think, it is redundant. rs.getObject("ID_PARENT")should return an Integerobject or null, if the column value actually was NULL. So it should even be possible to do something like:

我认为,这是多余的。rs.getObject("ID_PARENT")应该返回一个Integer对象或null,如果列值实际上是NULL. 因此,甚至应该可以执行以下操作:

if (rs.next()) {
  Integer idParent = (Integer) rs.getObject("ID_PARENT");
  if (idParent != null) {
    iVal = idParent; // works for Java 1.5+
  } else {
    // handle this case
  }      
}

回答by Peter Tillemans

AFAIK you can simply use

AFAIK你可以简单地使用

iVal = rs.getInt("ID_PARENT");
if (rs.wasNull()) {
  // do somthing interesting to handle this situation
}

even if it is NULL.

即使它是NULL。

回答by Chris

Another nice way of checking, if you have control the SQL, is to add a default value in the query itself for your int column. Then just check for that value.

如果您可以控制 SQL,另一种很好的检查方法是在查询本身中为您的 int 列添加一个默认值。然后只需检查该值。

e.g for an Oracle database, use NVL

例如,对于 Oracle 数据库,请使用 NVL

SELECT NVL(ID_PARENT, -999) FROM TABLE_NAME;

then check

然后检查

if (rs.getInt('ID_PARENT') != -999)
{
}

Of course this also is under the assumption that there is a value that wouldn't normally be found in the column.

当然,这也是假设存在通常不会在列中找到的值。

回答by Patrice IMBERT

Another solution:

另一种解决方案:

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

回答by BalusC

Just check if the field is nullor not using ResultSet#getObject(). Substitute -1with whatever null-case value you want.

只需检查该字段是否null使用ResultSet#getObject(). -1用您想要的任何空值替换。

int foo = resultSet.getObject("foo") != null ? resultSet.getInt("foo") : -1;

Or, if you can guarantee that you use the right DB column type so that ResultSet#getObject()really returns an Integer(and thus not Long, Shortor Byte), then you can also just typecast it to an Integer.

或者,如果您可以保证使用正确的 DB 列类型,以便ResultSet#getObject()真正返回一个Integer(因此不是Long, Shortor Byte),那么您也可以将其类型转换为Integer

Integer foo = (Integer) resultSet.getObject("foo");

回答by George

With java 8 you can do this:

使用 java 8,您可以执行以下操作:

Long nVal = Optional.ofNullable(resultSet.getBigDecimal("col_name"))
                    .map(BigDecimal::longValue).orElse(null));

In that case you ensure that the nVal will be null (and not zero) if the SQL value is NULL

在这种情况下,如果 SQL 值为 NULL,则确保 nVal 将为空(而不是零)

回答by Jacob Crofts

For convenience, you can create a wrapper class around ResultSet that returns null values when ResultSetordinarily would not.

为方便起见,您可以围绕 ResultSet 创建一个包装类,该类在ResultSet通常不会返回空值时返回空值。

public final class ResultSetWrapper {

    private final ResultSet rs;

    public ResultSetWrapper(ResultSet rs) {
        this.rs = rs;
    }

    public ResultSet getResultSet() {
        return rs;
    }

    public Boolean getBoolean(String label) throws SQLException {
        final boolean b = rs.getBoolean(label);
        if (rs.wasNull()) {
            return null;
        }
        return b;
    }

    public Byte getByte(String label) throws SQLException {
        final byte b = rs.getByte(label);
        if (rs.wasNull()) {
            return null;
        }
        return b;
    }

    // ...

}

回答by luchoct

Just an update with Java Generics.

只是 Java 泛型的更新。

You could create an utility method to retrieve an optional value of any Java type from a given ResultSet, previously casted.

您可以创建一个实用程序方法来从给定的 ResultSet 中检索任何 Java 类型的可选值,之前已进行转换。

Unfortunately, getObject(columnName, Class) does not return null, but the default value for given Java type, so 2 calls are required

不幸的是,getObject(columnName, Class) 不返回 null,而是给定 Java 类型的默认值,因此需要 2 次调用

public <T> T getOptionalValue(final ResultSet rs, final String columnName, final Class<T> clazz) throws SQLException {
    final T value = rs.getObject(columnName, clazz);
    return rs.wasNull() ? null : value;
}

In this example, your code could look like below:

在此示例中,您的代码可能如下所示:

final Integer columnValue = getOptionalValue(rs, Integer.class);
if (columnValue == null) {
    //null handling
} else {
    //use int value of columnValue with autoboxing
}

Happy to get feedback

很高兴得到反馈

回答by amine kriaa

You can call this method using the resultSet and the column name having Number type. It will either return the Integer value, or null. There will be no zeros returned for empty value in the database

您可以使用 resultSet 和具有 Number 类型的列名称调用此方法。它将返回整数值或空值。数据库中的空值不会返回零

private Integer getIntWithNullCheck(ResultSet rset, String columnName) {
    try {
        Integer value = rset.getInt(columnName);
        return rset.wasNull() ? null : value;
    } catch (Exception e) {
        return null;
    }
}