【问题标题】:Can't put varbinary from SQL into a byte[] in C# program using SqlDataReader and ExecuteReader无法使用 SqlDataReader 和 ExecuteReader 将 SQL 中的 varbinary 放入 C# 程序中的字节 []
【发布时间】:2013-10-27 17:55:21
【问题描述】:

我见过很多解决这个问题的方法,人们只会使用Command.ExecuteScalar as byte[];,但他们的 SQL 查询一次只能获取一个 varbinary 字段。我正在尝试选择大约 30k 行 varbinary 条目,但它们在 byte[] 中并反序列化。

这是我的代码:

public void MNAdapter()
    {
        IsoStorage retVal = new IsoStorage();

        SqlConnectionStringBuilder csb = new SqlConnectionStringBuilder();
        csb.DataSource = @"LocalMachine\SQLDEV";
        csb.InitialCatalog = "Support";
        csb.IntegratedSecurity = true;
        string connString = csb.ToString();

        using (SqlConnection conn = new SqlConnection(connString))
        {
            conn.Open();

            SqlCommand command = conn.CreateCommand();
            command.CommandText = @"SELECT S.Settings
from Support.dbo.SavedLocalSettings S
inner join WebCatalog.Published.People P
on P.PKey = S.PeopleLink
inner join WebCatalog.Published.Company C
on P.Link = C.PeopleList
where S.DateSaved >= GETDATE()-34
and C.PKey != '530F4622-C30D-DD11-A23A-00304834A8C9'
and C.PKey != '7BAF7229-9249-449E-BEA5-4B366D7ECCD1'
and C.PKey != 'CCBB2140-C30D-DD11-A23A-00304834A8C9'
and S.CompanyName not like 'Tech Support%'
Group By S.PeopleLink, S.Settings";

using (SqlDataReader reader = command.ExecuteReader(CommandBehavior.SequentialAccess))
                {
                    //DataTable dt = new DataTable();
                    //dt.Load(reader);

                    byte[] blob = null;
                    BinaryFormatter bf = new BinaryFormatter();
                    bf.Binder = new CustomBinder();
                    while (reader.Read())
                    {
                        reader.GetBytes(0,0,blob,0,100000);
                        Console.WriteLine(blob.ToString());
                        retVal = bf.Deserialize(new MemoryStream(blob)) as IsoStorage;
                    }
                }
            }
        }

我也尝试先将它们放入 Data tabla,尽管我认为这会是多余的,但它们会以整数形式读取。

我没有收到任何错误,数据正在进入数据读取器,但就像 reader.GetBytes(0,0,blob,0,100000); 甚至没有运行,因为 blob 保持为空。

【问题讨论】:

    标签: c# sql bytearray blob varbinary


    【解决方案1】:

    为什么不使用:

    blob = (byte[])reader.Items["Settings"];
    

    或者

    blob = (byte[])reader["Settings"];
    

    【讨论】:

      【解决方案2】:

      reader.GetBytes(0,0,blob,0,100000); 您希望此方法为您创建字节数组。它不会 - 它需要对现有数组的引用。你必须自己准备数组。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-12-16
        • 2021-11-23
        • 2019-09-13
        • 1970-01-01
        • 1970-01-01
        • 2015-12-03
        • 1970-01-01
        • 2018-11-14
        相关资源
        最近更新 更多