本文介绍了更新数据库,并对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 ...进行了修改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-29 08:34