内存在C#/ SQL 2005中读取BLOB数据的有效方法

Rub*_*ias 6 sql t-sql sql-server sql-server-2005

使用C#3.5读取SQL 2005图像字段的最有效内存方法是什么?

现在我有一个(byte[])cm.ExecuteScalar("...").

如果我无法将所有字段内容读入内存,那就太好了.

mar*_*c_s 4

请参阅此处这篇优秀文章或这篇博客文章,了解如何执行此操作的详细说明。

基本上,您需要使用 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();
Run Code Online (Sandbox Code Playgroud)

马克