如何直接将数据从DataTable添加到数据库表? [英] How can I add data from DataTable to database table directly?

查看:1576
本文介绍了如何直接将数据从DataTable添加到数据库表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将DataTable中的数据直接添加到数据库表?

我在互联网上搜索无法获取来自任何网站的信息。

I have searched on the internet not being able to get information from any site.

我有一个DataTable,现在我想将该数据添加到数据库表。

I have a DataTable and now I want to add that data to a database table.

 importData.Tables[1];
 for(int r = 0; r< totalrecoreds; r++;)
 {
         Array test[] =  importData.Tables[1].Rows[r].ItemArray.ToArray;
 }

我该怎么办?我必须使用for循环逐个添加数据,还有其他方法吗?

What can I do? Do I have to add data one by one using for loop or is there any other method?

推荐答案

如果DataTable的模式与数据库表的模式相同,那么您只需使用DataAdapter 插入数据。

Provided that the schema of the DataTable is the same as the schema of the database table you can just use a DataAdapter to insert the data.

using(var connection = new SqlConnection(...))
using(var adapter = new SqlDataAdapter("SELECT * FROM TABLENAME", connection))
using(var builder = new SqlCommandBuilder(adapter))
{
    adapter.UpdateCommand = builder.GetUpdateCommand();
    adapter.InsertCommand = builder.GetInsertCommand();
    adapter.DeleteCommand = builder.GetDeleteCommand();

    adapter.Update(importData.Tables[1]);
}

如果模式不同,您必须向DataAdapter添加映射,如 MSDN DataAdapter示例说明。

If the schemas differ you have to add mappings to the DataAdapter, like the MSDN DataAdapter example illustrates.

这篇关于如何直接将数据从DataTable添加到数据库表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆