使用 C# 从数据库读取图像?
我有这个查询:(
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(“行/列不存在数据”)总是被抛出到读取器上.IsDBNull(0) 语句,当列包含 null 时。
MSDN 说:
在调用类型化 get 方法(例如 GetByte、GetChar 等)之前调用此方法来查看是否存在空列值,以避免引发错误。
如何检查该列不包含 null 而不触发异常? 我是否以错误的方式处理这件事?
I've got this query:
SELECT PICTURE FROM LOGO WHERE LOGONO = ?
("PICTURE" is an Image column in SQL Server)
And this code to read the data:
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);
}
}
}
The problem is an InvalidOperationException ("No data exists for the row/column") always gets thrown on the reader.IsDBNull(0) statement when the column contains null.
MSDN says:
Call this method to see if there are null column values before calling the typed get methods (for example, GetByte, GetChar, and so on) to avoid raising an error.
How can I check that the column doesn't contain null without triggering the Exception? Am I going about this in the wrong way?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您需要调用 reader。Read() 在访问任何数据之前。 从 MSDN 文档中阅读:
You need to call reader.Read() before accessing any data. From the MSDN docs for Read:
您没有调用 reader.Read()。 由于您使用读取器,因此您要么需要检查 Read 是否对单个记录返回 true,要么使用 while 循环来迭代所有记录。
You did not call reader.Read(). Since your working with a reader, you either need to check if Read returns true for a single record, or use a while loop to iterate through all the records.
不是更好吗……
或者也许是简短的版本……
???
Isn't better...
or perhaps the short version...
???
我总是使用以下检查,它似乎一直对我有用。
I always use the following check and it seems to have always worked for me.