对于 SQL Server 的大量插入,您确实应该根据SqlBulkCopy
您的要求使用。
这是一个小例子。
// Set up your target fields and types
Dictionary<string, string> uploadFields = new Dictionary<string, string>()
{
{ "LocationId", "System.Int32" },
{ "CalendarDate", "System.DateTime" },
{ "IsWorkingDay", "System.Boolean" },
{ "SnapshotDate", "System.DateTime" }
};
// Set up a DataTable to hold the stuff we want to send.
DataTable massUpdate = new DataTable();
// Use the dictionary above to set up columns
uploadFields
.Keys
.ToList()
.ForEach(k => massUpdate.Columns.Add(k, Type.GetType(uploadFields[k])));
// Populate your datatable
foreach ( var thing in things )
{
DataRow row = massUpdate.NewRow();
row["LocationId"] = thing.Id;
row["CalendarDate"] = thing.Date;
row["IsWorkingDay"] = thing.IsWorkingDay;
row["SnapshotDate"] = DateTime.UtcNow;
massUpdate.Rows.Add(row);
}
// Finally, send the contents of the DataTable up via SqlBulkCopy.
// GetConnectionString
using (SqlConnection conn = new SqlConnection("Your connection string"))
{
using (SqlBulkCopy copy = new SqlBulkCopy(conn))
{
conn.Open();
foreach (var key in uploadFields.Keys)
{
copy.ColumnMappings.Add(key, key);
}
// Swap this table name with yoyr own.
copy.DestinationTableName = "DestinationTableName";
copy.WriteToServer(massUpdate);
conn.Close();
}
}
文件:-
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlbulkcopy.aspx