简体   繁体   中英

How to check for null values?

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

I have tried

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

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

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

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

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

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

Try:

If (data == System.DBNull)

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

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

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

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

DBNull is the value of a null column.

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

Assuming a SqlDataReader ... checking for null is :

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

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

SQL example

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

or

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM