【问题标题】:Reading an image from the database using C#?使用 C# 从数据库中读取图像?
【发布时间】:2010-11-01 21:27:58
【问题描述】:

我有这个查询:

SELECT PICTURE FROM LOGO WHERE LOGONO = ?

(“PICTURE”是 SQL Server 中的图像列)

以及读取数据的这段代码:

using (DbDataReader reader = command.ExecuteReader())
{
    if (reader.HasRows)
    {
        if (!reader.IsDBNull(0))
        {
            byte[] buffer = new byte[8000];
            while (reader.GetBytes(0, 0, buffer, 0, 8000) > 0)
                picture.AddRange(buffer);
        }
     }
}

问题是 InvalidOperationException(“行/列不存在数据”)总是在 reader 上抛出。当列包含 null 时,IsDBNull(0) 语句。

MSDN 说:

在调用类型化的 get 方法(例如,GetByte、GetChar 等)之前调用该方法查看是否有空列值,以避免引发错误。

如何在不触发异常的情况下检查列是否不包含 null?我是不是走错路了?

【问题讨论】:

    标签: c# image blob


    【解决方案1】:

    在访问任何数据之前,您需要调用 reader.Read()。来自 MSDN 文档的阅读:

    DataTableReader 的默认位置在第一条记录之前。因此,您必须调用 Read 才能开始访问任何数据。

    【讨论】:

      【解决方案2】:

      你没有调用 reader.Read()。由于您使用的是阅读器,因此您要么需要检查 Read 是否对单个记录返回 true,要么使用 while 循环遍历所有记录。

      if (reader.Read())
      {
        // handle single record
      }
      
      // or
      
      while (reader.Read())
      {
        // handle each record
      }
      

      【讨论】:

        【解决方案3】:

        不是更好...

        if (!reader.IsDBNull(#))
        {...}
        

        或者也许是简短的版本...

        reader.IsDBNull(#) ? [default] : [value];
        

        ???

        【讨论】:

          【解决方案4】:

          我总是使用以下检查,它似乎一直对我有用。

          if (reader[0] != null && reader[0] != DBNull.Value)
          {
          }
          

          【讨论】:

          • 试过了。不幸的是,没有运气。
          猜你喜欢
          • 2012-10-08
          • 2012-07-16
          • 1970-01-01
          • 2011-12-21
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-09-03
          相关资源
          最近更新 更多