简体   繁体   中英

Insert array into the table using SqlBulkCopy

I have a table with just two columns Id and Name. Where ID is auto incremented primary key. My array may contain couple of hundred items so I dont want to use any loop. My code looks like this:

DataTable dt = new DataTable();
dt.Columns.Add(new DataColumn("Name", typeof(string)));
foreach (string item in arrItems)
    dt.Rows.Add(item);

using (SqlBulkCopy bc = new SqlBulkCopy(connection, DB2BulkCopyOptions.KeepIdentity))
{   
    bc.DestinationTableName = destinationTableName;
    bc.ColumnMappings.Add("Name", "Name");
    bc.WriteToServer(dt);
}

I have written my code in this way. Is there any way to insert data from array(without creating table)?

You could create a class that wraps your Array and implements IDataReader. An instance of that class can be passed to the WriteToServer Method of SqlBulkCopy.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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