[英]Insert data from DataTable to database table
What is the easiest and most efficient way to insert data from a DataTable into a SQL Server database table?将数据从 DataTable 插入 SQL 服务器数据库表的最简单和最有效的方法是什么? For what it's worth, the DataTable and the database table have matching columns.对于它的价值,DataTable 和数据库表具有匹配的列。
What I am doing is transferring data from one database to another (separate instances, so I will be using my application as the intermediate "receiver/sender" of data).我正在做的是将数据从一个数据库传输到另一个数据库(单独的实例,因此我将使用我的应用程序作为数据的中间“接收者/发送者”)。 I can easily populate a DataTable with a SqlDataAdapater.Fill() call from the source database table.我可以使用来自源数据库表的 SqlDataAdapater.Fill() 调用轻松填充 DataTable。 But I'm trying to find the most proficient way to send that DataTable's data to the final destination database table.但我正在尝试找到将 DataTable 的数据发送到最终目标数据库表的最熟练方法。
Any suggestions/advice/opinions are much appreciated.非常感谢任何建议/建议/意见。
EDIT: the destination database table already exists.编辑:目标数据库表已经存在。
You should take a look at the SqlBulkCopy
class , particularly the overload of the WriteToServer
method that takes a DataTable
as a parameter .您应该查看SqlBulkCopy
class ,特别是采用DataTable
作为参数的WriteToServer
方法的重载。
If you want to be even more efficient, and you don't have the requirement to materialize the entire table into a DataSet
(or, you can process the contents as you move them in a forward-only manner), then use the overload of WriteToServer
that takes an IDataReader
run your query using the ExecuteReader
method on the SqlCommand
class instead of using a SqlDataAdapter
to load the entire table into memory.如果您想提高效率,并且不需要将整个表具体化为DataSet
(或者,您可以在以只进方式移动它们时处理内容),然后使用重载采用IDataReader
的WriteToServer
使用SqlCommand
class 上的ExecuteReader
方法运行查询,而不是使用SqlDataAdapter
将整个表加载到 memory 中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.