【发布时间】:2009-09-28 15:50:02
【问题描述】:
使用 C# 3.5 读取 SQL 2005 图像字段最节省内存的方法是什么?
现在我有一个(byte[])cm.ExecuteScalar("...")。
如果我不能将所有字段内容读入内存,那就太好了。
【问题讨论】:
标签: sql sql-server sql-server-2005 tsql
使用 C# 3.5 读取 SQL 2005 图像字段最节省内存的方法是什么?
现在我有一个(byte[])cm.ExecuteScalar("...")。
如果我不能将所有字段内容读入内存,那就太好了。
【问题讨论】:
标签: sql sql-server sql-server-2005 tsql
请参阅此出色的 article here 或此 blog post 以获得详细的说明。
基本上,您需要使用 SqlDataReader 并在创建它时为其指定 SequentialAccess - 然后您可以从数据库中读取(或写入)BLOB,以最适合您的大小。
基本上是这样的:
SqlDataReader myReader = getEmp.ExecuteReader(CommandBehavior.SequentialAccess);
while (myReader.Read())
{
int startIndex = 0;
// Read the bytes into outbyte[] and retain the number of bytes returned.
retval = myReader.GetBytes(1, startIndex, outbyte, 0, bufferSize);
// Continue reading and writing while there are bytes beyond the size of the buffer.
while (retval == bufferSize)
{
// write the buffer to the output, e.g. a file
....
// Reposition the start index to the end of the last buffer and fill the buffer.
startIndex += bufferSize;
retval = myReader.GetBytes(1, startIndex, outbyte, 0, bufferSize);
}
// write the last buffer to the output, e.g. a file
....
}
// Close the reader and the connection.
myReader.Close();
马克
【讨论】:
这里的技巧是在顺序模式下使用 ExecuteReader,并从IDataReader 读取数据。 Here's a version for CLOBs - BLOB 几乎相同,但具有 byte[] 和 GetBytes(...)。
类似:
using (var reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess))
{
byte[] buffer = new byte[8040]; // or some multiple (sql server page size)
while (reader.Read()) // each row
{
long dataOffset = 0, read;
while ((read = reader.GetBytes(
colIndex, dataOffset, buffer, 0, buffer.Length)) > 0)
{
// TODO: process "read"-many bytes from "buffer"
dataOffset += read;
}
}
}
【讨论】: