使用 SqlDataReader (C#) 从 SQL Server 读取多个字节的最有效方法是什么 [英] What is the most efficient way to read many bytes from SQL Server using SqlDataReader (C#)

查看:56
本文介绍了使用 SqlDataReader (C#) 从 SQL Server 读取多个字节的最有效方法是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 SqlDataReader 从 SQL Server 读取字节 (8-16 K) 的最有效方法是什么.我似乎知道两种方法:

What is the most efficient way to read bytes (8-16 K) from SQL Server using SqlDataReader. It seems I know 2 ways:

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;
}

reader.GetSqlBinary(columnIndex).Value

数据类型为 IMAGE

The data type is IMAGE

推荐答案

对于那个 blob 大小,我会选择 GetSqlBinary.下面我还包含了一个 Base64 编码示例;像这样:

For that blob size, I would go with GetSqlBinary. Below I've also included a Base64 encode example; 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 
        }
    }
}

这篇关于使用 SqlDataReader (C#) 从 SQL Server 读取多个字节的最有效方法是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆