【问题标题】:What is the best way to find out whether image column is null or not?找出图像列是否为空的最佳方法是什么?
【发布时间】:2013-02-01 11:14:36
【问题描述】:

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

【问题讨论】:

  • 当没有图像数据时,您应该尝试打印出所有关于该值的信息 - 在第二种形式中使用 else。这应该会引导你找到答案

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


【解决方案1】:

你应该这样检查DbNull

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

【讨论】:

猜你喜欢
  • 2020-09-07
  • 2020-12-08
  • 1970-01-01
  • 2014-02-07
  • 1970-01-01
  • 2013-05-23
  • 1970-01-01
  • 2023-03-18
  • 2018-06-07
相关资源
最近更新 更多