Skip to content

Instantly share code, notes, and snippets.

@paladique
Last active September 24, 2016 00:45
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save paladique/613e6ba50af1c27a1388f904195bb51e to your computer and use it in GitHub Desktop.
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