如何检查空值?

时间:2023-02-07 10:04:26

I have an integer column that may have a number or nothing assigned to it (i.e. null in the database). How can I check if it is null or not?

我有一个整数列,可能有一个数字或没有分配给它(即数据库中为null)。如何检查它是否为空?

I have tried

我试过了

if(data.ColumnName == null)
{
    ...
}

This doesn't work either (as SubSonic does not use nullable types (when applicable) for ActiveRecord)

这也不起作用(因为SubSonic不为ActiveRecord使用可空类型(适用时))

if(data.ColumnName.HasValue)
{
    ...
}

If the value stored in the database is 0, then this wouldn't help:

如果存储在数据库中的值为0,那么这将无济于事:

if(data.ColumnName == 0 /* or 0x000? */)
{
    ...
}

The same problem could also occur with DateTime fields as well.

DateTime字段也可能出现同样的问题。

5 个解决方案

#1


Try:

If (data == System.DBNull)

如果(data == System.DBNull)

#2


Found out how to do it. SubSonic has a method for getting the value as an object to allow a null check:

找到了怎么做。 SubSonic有一种方法可以将值作为对象来获取以进行空检查:

if(data.GetColumnValue("Column Name") == null)
{
    ...
}

#3


if your data variable is a strongly typed datarow, this might help :

如果您的数据变量是强类型数据行,这可能会有所帮助:

if(data.IsNull("ColumnName")) { ... }

#4


DBNull is the value of a null column.

DBNull是空列的值。

DBNull is a value type. Value types cannot be null.

DBNull是一种值类型。值类型不能为null。

Assuming a SqlDataReader ... checking for null is :

假设一个SqlDataReader ...检查null是:

if (reader["colname") == DBNull.Value)

if(reader [“colname”)== DBNull.Value)

#5


When querying the database handle the null there, makes your life a lot easier in the code

查询数据库时处理null,使代码中的生活变得更容易

SQL example

SELECT isNull(columnName, 0) FROM TABLENAME...

or

Select isNUll(columnName, 'N/A') FROM TABLENAME ...

#1


Try:

If (data == System.DBNull)

如果(data == System.DBNull)

#2


Found out how to do it. SubSonic has a method for getting the value as an object to allow a null check:

找到了怎么做。 SubSonic有一种方法可以将值作为对象来获取以进行空检查:

if(data.GetColumnValue("Column Name") == null)
{
    ...
}

#3


if your data variable is a strongly typed datarow, this might help :

如果您的数据变量是强类型数据行,这可能会有所帮助:

if(data.IsNull("ColumnName")) { ... }

#4


DBNull is the value of a null column.

DBNull是空列的值。

DBNull is a value type. Value types cannot be null.

DBNull是一种值类型。值类型不能为null。

Assuming a SqlDataReader ... checking for null is :

假设一个SqlDataReader ...检查null是:

if (reader["colname") == DBNull.Value)

if(reader [“colname”)== DBNull.Value)

#5


When querying the database handle the null there, makes your life a lot easier in the code

查询数据库时处理null,使代码中的生活变得更容易

SQL example

SELECT isNull(columnName, 0) FROM TABLENAME...

or

Select isNUll(columnName, 'N/A') FROM TABLENAME ...