一次将整个 DataTable 插入数据库而不是逐行插入数据库?

Insert entire DataTable into database at once instead of row by row?(一次将整个 DataTable 插入数据库而不是逐行插入数据库?)
本文介绍了一次将整个 DataTable 插入数据库而不是逐行插入数据库?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 DataTable,需要将整个内容推送到数据库表中.

I have a DataTable and need the entire thing pushed to a Database table.

我可以用一个 foreach 把它全部放在那里,一次插入每一行.由于有几千行,这会非常缓慢.

I can get it all in there with a foreach and inserting each row at a time. This goes very slow though since there are a few thousand rows.

有没有什么方法可以更快地一次性完成整个数据表?

Is there any way to do the entire datatable at once that might be faster?

DataTable 的列数少于 SQL 表.其余的应为空.

The DataTable has less columns than the SQL table. the rest of them should be left NULL.

推荐答案

我发现 SqlBulkCopy 是一种简单的方法,并且不需要在 SQL Server 中编写存储过程.

I discovered SqlBulkCopy is an easy way to do this, and does not require a stored procedure to be written in SQL Server.

这是我如何实现它的示例:

Here is an example of how I implemented it:

// take note of SqlBulkCopyOptions.KeepIdentity , you may or may not want to use this for your situation.  

using (var bulkCopy = new SqlBulkCopy(_connection.ConnectionString, SqlBulkCopyOptions.KeepIdentity))
{
      // my DataTable column names match my SQL Column names, so I simply made this loop. However if your column names don't match, just pass in which datatable name matches the SQL column name in Column Mappings
      foreach (DataColumn col in table.Columns)
      {
          bulkCopy.ColumnMappings.Add(col.ColumnName, col.ColumnName);
      }

      bulkCopy.BulkCopyTimeout = 600;
      bulkCopy.DestinationTableName = destinationTableName;
      bulkCopy.WriteToServer(table);
}

这篇关于一次将整个 DataTable 插入数据库而不是逐行插入数据库?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)