繁体   English   中英

将SqlCommand列(多行)读入单个C#byte []数组

[英]Read a SqlCommand column (multiple rows) into a single C# byte[] array

给定一个带有数据的SQL表Document

ID  Content     ByteLength  Sequence
1   Part1...    945669      1
1   Part2...    945669      2
1   Part3...    945669      3

...

2   Part1...    45234       1
2   Part2...    45234       2

哪里:

Document.Content = Up to 32KB of data
Document.ByteLength = Total data in bytes for the Document ID
Document.Sequence = Order of content in the Document ID

如何将所有Document.Content读入单字节数组byte[] Content

using (var command = new SqlCommand("SELECT Content FROM Document WHERE ID=1 ORDER BY Sequence", connection))
    using (var reader = command.ExecuteReader())
    {
        while(reader.Read())
        {
            // What goes here?

            // if we just want one row:
            //var fileBytes = (byte[])reader.GetValue(0); // read the file data from the selected row (first column in above query)
        }
    }

鉴于此Content字段包含文本数据的事实,您可以在读取content字段时简单地使用StringBuilder添加数据

using (var command = new SqlCommand("SELECT Content FROM Document WHERE ID=1 ORDER BY Sequence", connection))
using (var reader = command.ExecuteReader())
{
    // Set a large enough initial capacity
    StringBuilder sb = new StringBuilder(32767);
    while(reader.Read())
    {
        sb.Append(reader.GetString(0));
    }
}

现在,在循环出口处,所有内容都在StringBuilder缓冲区中,您可以使用

byte[] buffer = System.Text.Encoding.UTF8.GetBytes(sb.ToString());

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM