问题定义: 我在 SQL Server 数据库中有一个表。该表有一列图像类型,它允许空值。我将使用 SqlDataReader 读取此表并显示图像(如果可用)。
我第一次尝试的是:为了检查图像列是否为空,我这样做了
SqlDataReader reader = command.ExecuteReader(); // command is a SqlCommand
while(reader.Read())
{
if(reader["Image"] != null) // Image is a column name of the table
{
//Do something
}
}
结果: 但它永远不会等于 null(我还检查了 Equal 方法)。即使没有插入数据,该列也永远不会为空(在 SQL Server 中我可以看到它实际上是空的)
我第二次尝试了什么: 所以我尝试了这段代码及其工作,但我想知道为什么它不返回 null。
SqlDataReader reader = command.ExecuteReader(); // command is a SqlCommand
while(reader.Read())
{
if(reader["Image"].GetType() != typeof(System.DBNull))
{
//Do something
}
}
问题:有什么办法可以解释这种行为吗?如果有更好的方法来查明 SQL Server 表中图像类型的列是否为空,我会很高兴。
请您参考如下方法:
您应该以这种方式检查 DbNull。
if(reader["Image"] != DbNull.Value) // Image is a column name of the table
{
//Do something
}
