【问题标题】:How can I add data from DataTable to database table directly?如何将 DataTable 中的数据直接添加到数据库表中?
【发布时间】:2012-03-08 18:09:40
【问题描述】:

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

我在互联网上进行了搜索,但无法从任何网站获取信息。

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

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

我能做什么?我必须使用for循环一一添加数据还是有其他方法?

【问题讨论】:

  • 您的代码与您的问题有何关联?
  • 我必须编写 for 循环才能将数据添加到数据库或什么?
  • 请考虑提供有关您正在使用的 DBMS、importData 等背后的更多具体信息。简短的回答是不,您当然有不同的方法来避免像使用 ORM、Linq 这样的循环,和其他选项

标签: c# .net sql-server dataset


【解决方案1】:

只要DataTable的schema和数据库表的schema一致就可以use a DataAdapter插入数据。

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 添加映射,如 the MSDN DataAdapter example 所示。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多