找出图像列是否为空的最佳方法是什么?

时间:2013-02-16 16:13:03

标签: c# sql-server image ado.net dbnull

问题定义: 我在SQL Server数据库中有一个表。此表有一个image类型的列,它允许空值。我将使用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 Tables中Image类型的列是否为null,我将很高兴。

1 个答案:

答案 0 :(得分:4)

您应该以这种方式检查DbNull

if(reader["Image"] != DbNull.Value)     // Image is a column name of the table
{
    //Do something
}
相关问题