Ian*_*ose 7 .net sql-server ado.net
有关此问题的背景信息,请参阅"如何在不创建大缓冲区的情况下将.NET对象的大图形序列化为SQL Server BLOB?"现在它具有很大的赏金.
我希望能够使用流对象从在SQL Server行BLOB字段读/写数据到/,而不必把所有的数据到临时缓冲区.
如果可以做到以上......
由于Streams类有很多CanXXX()
方法,所以所有方法都不能使用所有流来接受流输入/输出.
那么在向/从SQL Server发送数据时,流必须能够与ADO.NET一起工作吗?
我希望有一个标准的流,我可以将其传递给其他API.
到目前为止,这两个答案只涵盖从SqlServer获取数据,而不是将数据发送到SqlServer.
以下是以块的形式读取数据的示例:
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)