C#对象空值检查

8

我使用DataReader读取我的数据库。

有些行没有fdate值。

因此,当我将空日期转换为DateTime时会出错。

我该如何检查字段是否为空?

AdsCommand cmd = conn.CreateCommand();
cmd.CommandText = "select name,fdate from abc";

AdsDataReader reader = cmd.ExecuteReader();

DateTime flsdate = (reader["fdate"].Equals(null))? Convert.ToDateTime(reader["fdate"]) : DateTime.Today;

我尝试使用“Equals”,但它不起作用。

有人知道如何检查空对象以避免转换错误吗?

谢谢!


使用 ==!= 而不是 .Equals。此外,您可能需要检查 DBNull,而不仅仅是 null。(是的,它们是不同的)。 - Servy
可能会有重复吗?http://stackoverflow.com/questions/3432974/datareader-is-null-or-empty - King Chan
6个回答

11

所有人都告诉你如何解决问题,我试图给你提供关于NULL和DBNull之间的区别的信息。

  • nullDBNull 是不同的。

  • null 不是任何类型的实例。DBNull是一个单例类,只有一个实例:DBNull.Value

  • null 表示无效引用,而 DBNull.Value 表示DB中不存在的值。

  • DBNull.Value是数据库提供程序为表中不存在的值提供的值。

在这种情况下,(reader["fdate"].Equals(null))不正确。您必须使用DBNull.Value进行检查。如果它是DBNull类型或等于DBNull.Value,则分配任何您想要的值。


3
+1 如果实际解释了一些内容。我稍微编辑了一下,请回滚任何您不同意的更改。 - phoog


4
在这种情况下,我喜欢使用引用类型(例如varchar的字符串)或可空包装值类型(例如DateTime?)来表示可为空的数据库列。这样,您更准确地表示了程序中的数据库模式。
这还允许您更清晰地编写转换逻辑,使用以下格式:
DateTime? fdate = datareader["fdate"] as DateTime?;

如果数据读取器返回的结果是DbNull,这个转换将失败,fdate将被设置为默认值(DateTime?),也就是null。此时,您可以通过检查可空类型是否有值(fdate.HasValue),如果没有,则使用默认值DateTime.Today来获取您真正想要的值。


2
DateTime flsdate = reader["fdate"].Equals(DBNull.Value)
    ? Convert.ToDateTime(reader["fdate"])
    : DateTime.Today;

但是将日期默认设置为今天似乎有风险。我建议进行以下更改:

DateTime? flsdate = reader["fdate"].Equals(DBNull.Value)
    ? Convert.ToDateTime(reader["fdate"])
    : (DateTime?)null;

此外,如果“fdate”列的基础类型已经是 DateTime,请勿使用 System.Convert:
DateTime? flsdate = reader["fdate"].Equals(DBNull.Value)
    ? (DateTime?)reader["fdate"])
    : null;

1

请尝试以下方法:

DateTime flsdate = reader["fdate"] != null && reader["fdate"] != System.DbNull.Value
    ? DateTime.ParseExact(reader["fdate"]) 
    : DateTime.Today;

1
DateTime flsdate = DateTime.Today;
if(reader["fdate"] != null)
    flsdate = Convert.ToDateTime(reader["fdate"])

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接