使用C#3.5读取SQL 2005映像字段的最有效内存方式是什么?
现在我有(byte[])cm.ExecuteScalar("...")
。
如果我无法将所有字段内容读入内存,那就太好了。
答案 0 :(得分:4)
请参阅此优秀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();
马克
答案 1 :(得分:2)
这里的技巧是在顺序模式下使用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;
}
}
}