For when you need to take a bunch of things and insert them into a table
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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