2012-02-17 50 views
1

如何直接將DataTable中的數據添加到數據庫表中?如何直接將數據從DataTable添加到數據庫表中?

我已經在互聯網上搜索不能從任何網站獲取信息。

我有一個DataTable,現在我想將該數據添加到數據庫表。

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

我該怎麼辦?我是否必須使用for循環逐個添加數據還是有其他方法嗎?

+1

你的代碼與你的問題有什麼關係? – Mithrandir 2012-02-17 10:34:49

+0

我必須寫回路來添加數據到數據庫或什麼? – bkac 2012-02-17 10:36:31

+0

請考慮給出關於您正在使用的DBMS,'importData'背後的更多具體信息等。簡短回答是否,您肯定有不同的方式來避免使用ORM,Linq和其他選項 – 2012-02-17 10:39:59

回答

3

前提是DataTable的模式與數據庫表的模式相同,您可以只插入數據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說明。

相關問題