How can I add data from DataTable to database table directly?

天涯浪子 提交于 2019-12-11 05:18:58

问题


How can I add data from a DataTable to a database table directly?

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

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;
 }

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


回答1:


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]);
}

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



来源:https://stackoverflow.com/questions/9326622/how-can-i-add-data-from-datatable-to-database-table-directly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!