从SQL表中向DataTable插入行

时间:2012-07-06 19:16:23

标签: c# .net ado.net datatable dataadapter

我的C#程序中有一个Datatable,我想从SQL Server的临时表中INSERT行。 dataAdapter.FILL()方法写入整个数据表。我需要保留DataTable中的记录,并将临时表中存在的记录添加回DataTable

我没有看到DA方法,它们似乎都回到了除FILL之外的SQL Server表。这可能吗?

2 个答案:

答案 0 :(得分:2)

合并DataTables

DataTable dttemp = new DataTable();

dataAdapter.Fill(dtTemp);

originaldatatable.Merge(dtTemp);

答案 1 :(得分:0)

// Now, open a database connection using the Microsoft.Jet.OLEDB provider.
// The "using" statement ensures that the connection is closed no matter what.
using (var connection = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data      source=Northwind.mdb"))
{
    connection.Open();

// Create an OleDbDataAdapter and provide it with an INSERT command.
var adapter = new OleDbDataAdapter();
adapter.InsertCommand = new OleDbCommand("INSERT INTO Shippers (CompanyName, Phone) VALUES (@CompanyName , @Phone)", connection);
adapter.InsertCommand.Parameters.Add("CompanyName", OleDbType.VarChar, 40, "CompanyName");
adapter.InsertCommand.Parameters.Add("Phone", OleDbType.VarChar, 24, "Phone");

adapter.Update(data);
}