1

问题定义: 我在 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 表中 Image 类型的列是否为空,我会很高兴。

4

1 回答 1

4

你应该只检查DbNull这种方式。

if(reader["Image"] != DbNull.Value)     // Image is a column name of the table
{
    //Do something
}
于 2013-02-16T16:18:56.143 回答