Skip to content

Instantly share code, notes, and snippets.

@paladique paladique/bulkcopy.cs
Last active Sep 24, 2016

Embed
What would you like to do?
For when you need to take a bunch of things and insert them into a table
public bool BulkCopy(object[] things, int id)
{
var dt = new DataTable("MyTable");
dt.Columns.Add("mythings", typeof(string));
dt.Columns.Add("ID", typeof(Int32));
foreach (var item in things)
{
var row = dt.NewRow();
row[0] = item;
row[1] = id;
dt.Rows.Add(row);
}
try
{
using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["SODB"].ToString()))
{
SqlBulkCopy bulkCopy =
new SqlBulkCopy(
connection,
SqlBulkCopyOptions.TableLock |
SqlBulkCopyOptions.FireTriggers |
SqlBulkCopyOptions.UseInternalTransaction,
null);
bulkCopy.DestinationTableName = "[TableToInsertThingsInto]";
connection.Open();
bulkCopy.WriteToServer(dt);
connection.Close();
}
}
catch (Exception)
{
return false;
throw;
}
return true;
}
//Adapted from https://blogs.msdn.microsoft.com/nikhilsi/2008/06/11/bulk-insert-into-sql-from-c-app/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.