[英]What is the most efficient way to read many bytes from SQL Server using SqlDataReader (C#)
What is the most efficient way to read bytes (8-16 K) from SQL Server using SqlDataReader. 使用SqlDataReader从SQL Server读取字节(8-16 K)的最有效方法是什么。 It seems I know 2 ways: 看来我知道2种方式:
byte[] buffer = new byte[4096];
MemoryStream stream = new MemoryStream();
long l, dataOffset = 0;
while ((l = reader.GetBytes(columnIndex, dataOffset, buffer, 0, buffer.Length)) > 0)
{
stream.Write(buffer, 0, buffer.Length);
dataOffset += l;
}
and 和
reader.GetSqlBinary(columnIndex).Value
The data type is IMAGE 数据类型为IMAGE
GetSqlBinary will load the whole data into memory while your first approach will read it in chunks which will take less memory especially if you need to only process the binary in parts. GetSqlBinary会将整个数据加载到内存中,而您的第一种方法将以块的形式读取它,这将占用更少的内存,尤其是如果您只需要部分处理二进制文件时。 But once again it depends on what you are going to do with the binary and how it will be processed. 但是,这再次取决于二进制文件的处理方式和处理方式。
For that blob size, I would go with GetSqlBinary. 对于那个blob大小,我将使用GetSqlBinary。 Below I've also included a Base64 encode example; 下面,我还提供了一个Base64编码示例; something like this: 像这样的东西:
using (SqlConnection con = new SqlConnection("...")) {
con.Open();
using (SqlCommand cmd = con.CreateCommand()) {
cmd.CommandText = "SELECT TOP 1 * FROM product WHERE DATALENGTH(picture)>0";
using (SqlDataReader reader = cmd.ExecuteReader()) {
reader.Read();
byte[] dataBinary = reader.GetSqlBinary(reader.GetOrdinal("picture")).Value;
string dataBase64 = System.Convert.ToBase64String(dataBinary, Base64FormattingOptions.InsertLineBreaks);
//TODO: use dataBase64
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.