Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. In most of the other areas we're using Entity model which uses byte arrays to represent binary data in SQL. However, SqlBulkCopy seems to be confusing byte[] with string. 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."

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.

Any help would be greatly appreciated

like image 603
Cogwheel Avatar asked Jan 04 '10 19:01

Cogwheel


People also ask

What is the use of WriteToServer DataTable method of SqlBulkCopy class?

WriteToServer(DataTable)Copies all rows in the supplied DataTable to a destination table specified by the DestinationTableName property of the SqlBulkCopy object.

What is the use of SqlBulkCopy command?

The SqlBulkCopy class can be used to write data only to SQL Server tables. However, the data source is not limited to SQL Server; any data source can be used, as long as the data can be loaded to a DataTable instance or read with a IDataReader instance.

Does SqlBulkCopy use transaction?

By default, a bulk copy operation is its own transaction. When you want to perform a dedicated bulk copy operation, create a new instance of SqlBulkCopy with a connection string, or use an existing SqlConnection object without an active transaction.


1 Answers

Instead of:

table.Columns.Add("Data");

Add the "Data" column as a binary:

table.Columns.Add("Data", typeof(Byte[]));
like image 153
Andomar Avatar answered Nov 02 '22 05:11

Andomar