当需要插入大量数据时,使用SqlBuckCopy效率较高,现将要插入的数据添加到DataTable中。如果新生成ID号,使用SqlBulkCopyOptions.UseInternalTransaction,保留原来的ID,用SqlBulkCopyOptions.KeepIdentity
//sqlBulkCopy
public static string BatchInsertBySqlBulkCopy(DataTable dt, string tableName)
{
try
{
using (SqlBulkCopy sbc = new SqlBulkCopy(ConnectionString, SqlBulkCopyOptions.UseInternalTransaction))
{
sbc.BatchSize = dt.Rows.Count;
sbc.BulkCopyTimeout = 10;
sbc.DestinationTableName = tableName;
for (int i = 0; i < dt.Columns.Count; i++)
{
sbc.ColumnMappings.Add(dt.Columns[i].ColumnName, dt.Columns[i].ColumnName);
}
sbc.WriteToServer(dt);
}
}
catch (Exception e)
{
return e.Message;
}
return "success";
}