如何从/到SQL Server BLOB字段流数据?

Ian*_*ose 7 .net sql-server ado.net

有关此问题的背景信息,请参阅"如何在不创建大缓冲区的情况下将.NET对象的大图形序列化为SQL Server BLOB?"现在它具有很大的赏金.

我希望能够使用对象从在SQL Server行BLOB字段读/写数据到/,而不必把所有的数据到临时缓冲区.


如果可以做到以上......

由于Streams类有很多CanXXX()方法,所以所有方法都不能使用所有流来接受流输入/输出.

那么在向/从SQL Server发送数据时,流必须能够与ADO.NET一起工作吗?


我希望有一个标准的流,我可以将其传递给其他API.

到目前为止,这两个答案只涵盖从SqlServer获取数据,而不是数据发送到SqlServer.

Dar*_*rov 5

以下是以块的形式读取数据的示例:

    using (var conn = new SqlConnection(connectionString))
    using (var cmd = conn.CreateCommand())
    {
        conn.Open();
        cmd.CommandText = "select somebinary from mytable where id = 1";
        using (var reader = cmd.ExecuteReader())
        {
            while (reader.Read())
            {
                byte[] buffer = new byte[1024]; // Read chunks of 1KB
                long bytesRead = 0;
                long dataIndex = 0;
                while ((bytesRead = reader.GetBytes(0, dataIndex, buffer, 0, buffer.Length)) > 0)
                {
                    byte[] actual = new byte[bytesRead];
                    Array.Copy(buffer, 0, actual, 0, bytesRead);
                    // TODO: Do something here with the actual variable, 
                    // for example write it to a stream
                    dataIndex += bytesRead;
                }
            }

        }
    }
Run Code Online (Sandbox Code Playgroud)


Mar*_*ell 1

您不会将所有数据放入缓冲区;您通常会运行一个循环,缓冲 8040 字节的某个倍数(与页面大小相关),每次添加 BLOB WRITETEXT/ UPDATETEXTforimageUPDATE.WRITEfor varbinary(max)这是一个较旧的示例(使用image,抱歉)。

同样,当读取数据时,您希望将小缓冲区中的数据泵送到其他目的地(http 响应、网络、文件等)。像这样的东西(虽然我不太喜欢他处理 EOF / 分块的方式;我会检查 +ve 字节读取)。