使用对 DataTable 所做的更改更新数据库...混乱 [英] Update database with changes made to DataTable... confusion
本文介绍了使用对 DataTable 所做的更改更新数据库...混乱的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我使用 DataAdapter.Fill(DataTable);
填充 DataTable,然后使用如下简单的内容更改 DataTable 中的一行:DataTable.Rows[0]["Name"] = "New Name";
如何轻松地将这些更改保存回数据库?我以为我可以调用 DataAdapter.Update(DataTable);
但我读到它只适用于 TableAdapter(?).
If I fill a DataTable with DataAdapter.Fill(DataTable);
and then make changes to a row in the DataTable with something simple like this: DataTable.Rows[0]["Name"] = "New Name";
how can I easily save those changes back to the database? I assumed I could call DataAdapter.Update(DataTable);
but I read that only works with a TableAdapter(?).
推荐答案
这是一个实际有用的答案,以防其他人需要知道如何执行此操作:
Here is an actual helpful answer in case anyone else needs to know how to do this:
string selectStatement = "SELECT * FROM Contact";
System.Data.DataTable dt = new System.Data.DataTable();
SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString);
conn.Open();
SqlDataAdapter sqlDa = new SqlDataAdapter();
sqlDa.SelectCommand = new SqlCommand(selectStatement, conn);
SqlCommandBuilder cb = new SqlCommandBuilder(sqlDa);
sqlDa.Fill(dt);
dt.Rows[0]["Name"] = "Some new data here";
sqlDa.UpdateCommand = cb.GetUpdateCommand();
sqlDa.Update(dt);
这篇关于使用对 DataTable 所做的更改更新数据库...混乱的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文