简体   繁体   English

如何在DataTable中使用SqlBulkCopy和二进制数据(byte [])?

[英]How can I use SqlBulkCopy with binary data (byte[]) in a DataTable?

I'm trying to use SqlBulkCopy to import a bunch of data to our website. 我正在尝试使用SqlBulkCopy将一堆数据导入我们的网站。 In most of the other areas we're using Entity model which uses byte arrays to represent binary data in SQL. 在大多数其他领域,我们使用的是Entity模型,它使用字节数组来表示SQL中的二进制数据。 However, SqlBulkCopy seems to be confusing byte[] with string. 但是,SqlBulkCopy似乎使byte []与字符串混淆。 Everything seems to be working fine except for this one binary column which throws an exception: "The given value of type String from the data source cannot be converted to type binary of the specified target column." 除了抛出异常的一个二进制列之外,一切似乎都工作正常:“数据源中String类型的给定值无法转换为指定目标列的二进制类型。”

I've created a small test case to illustrate the problem: 我创建了一个小测试用例来说明问题:

using System.Data;
using System.Data.SqlClient;

namespace SqlBulkCopyTest
{
    class Program
    {
        static void Main(string[] args)
        {
            DataTable table = new DataTable("BinaryData");
            table.Columns.Add("Data");

            for (int i = 0; i < 10; i++)
            {
                var row = table.NewRow();
                row["Data"] = new byte[5] { 1, 2, 3, 4, 5 };
                table.Rows.Add(row);
            }

            using (var connection = 
                new SqlConnection("Data Source=localhost\\sqlexpress;Initial Catalog=TestBulkCopy;Integrated Security=True"))
            {
                connection.Open();
                using (var copier = new SqlBulkCopy(connection))
                {
                      copier.DestinationTableName = table.TableName;
/* EXCEPTION HERE: */ copier.WriteToServer(table);
                }
            }
        }
    }
}

This uses a test database with a BinaryData table which has a single binary(5) column named Data . 这使用带有BinaryData表的测试数据库,该表具有名为Data的单个binary(5)列。

Any help would be greatly appreciated 任何帮助将不胜感激

Instead of: 代替:

table.Columns.Add("Data");

Add the "Data" column as a binary: 将“数据”列添加为二进制:

table.Columns.Add("Data", typeof(Byte[]));

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

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