代码之家  ›  专栏  ›  技术社区  ›  Rubens Farias

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

  •  6
  • Rubens Farias  · 技术社区  · 15 年前

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

    (byte[])cm.ExecuteScalar("...") .

    2 回复  |  直到 15 年前
        1
  •  4
  •   marc_s Anurag    15 年前

    article here 还是这个 blog post 关于如何做的详细解释。

    基本上,您需要使用SqlDataReader并指定 SequentialAccess

    基本上是这样的:

    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();
    

    马克

        2
  •  2
  •   Community dbr    7 年前

    IDataReader Here's a version for CLOBs -斑点实际上是相同的,但有一个 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;
            }
        }
    }