C# DataAdapter.Update()不更新数据库中的数据

C# DataAdapter.Update()不更新数据库中的数据,c#,ado.net,C#,Ado.net,我有个任务要求我更新northwind数据库, 我做了所有的事情,就像下面的教程所说的 我使用DataAdapter.Filltable填充DataTable 我使用CommangBuilder生成删除、插入和更新命令 我还为表设置了主键: DataColumn[] employees_keys = new DataColumn[2]; employees_keys[0] = employees.Columns["EmployeeID"]; employees_table.PrimaryKey

我有个任务要求我更新northwind数据库, 我做了所有的事情,就像下面的教程所说的

我使用DataAdapter.Filltable填充DataTable

我使用CommangBuilder生成删除、插入和更新命令

我还为表设置了主键:

DataColumn[] employees_keys = new DataColumn[2];
employees_keys[0] = employees.Columns["EmployeeID"];
employees_table.PrimaryKey = employees_keys; 
现在我尝试删除并添加一行:

// accepts an employee object and creates a new new row with the appropriate values for 
// an employee table row 
DataRow row = ConvertEmployeeToRow(employeeToAdd);
employee_table.Rows.Add(row);`
以及删除一行:

DataRow row = employees.Rows.Find(employeeToDismiss.ID);
employees.Rows.Remove(row); 
我还应该指出,我试图使用row.SetAdded和row.Delete

无论如何,在我试图更新数据库的最后

int k = employees_adapter.Update(employees_table);
在添加的行上,有时k会被赋值,在remove-never上,在任何一种情况下,数据库本身都不会真正得到更新


了解我做错了什么吗?

确保在调用Update后调用employee_table.AcceptChanges将更改保存到数据库中

我有点困惑,您的SqlDataAdapter名称是adapter,您正在employees_adapter中进行更新。使用SqlDataAdapter的步骤非常简单,只需按照以下步骤操作即可

第一步:

第2步:

获取数据集中的数据后,开始对其进行操作

插入:

 DataRow MyRow = employees_table.NewRow();
 //Now Fill data in MyRow
 employees_table.Tables[0].Rows.Add(MyRow);
 adapter.Update(employees_table);
删除:

 /get only the rows you want
 DataRow[] result = employees_table.Select("ID ="+id); //id will be provided by you
 //Now do here data updation 
 adapter.delete(result);
 adapter.Update(employees_table);
wise一样,您可以应用更新。但在进行任何更改后,必须调用“adapter.Updateemployees\u table”

检查CommandBuilder是否真的为您发出了更新命令,如下所示:

MessageBox.Show(adapter.UpdateCommand.CommandText);

如果主键信息丢失,则根本不会生成更新命令

据我所知,dataadapter作为一个名为AcceptChangeDuringUpdate、adapter.AcceptChangesDuringUpdate的属性,其默认设置为trueYou's right-我将dataadapter和DataTable混淆了。很抱歉。我又遇到了这个问题,我不知道我应该调用acceptchanges一段时间,但是谢谢。据我所知,dataadapter作为一个名为AcceptChangeDuringUpdate、adapter.AcceptChangesDuringUpdate的属性,默认设置为true,dataadapter没有一个名为AcceptChanges的函数,比如DataTable、DataSet或DataRow,此外,我认为问题在于我试图调用这些更改的northwind数据库,它似乎在更新,但在一两分钟后又会更改回来,可能存在某种机制,可以恢复所有默认值。对于插入,无需获取主键,因为在north wind中,员工的键列标识规范设置为“是”…感谢我发现我所做的一切都很好,请接受将删除的行标记为“已删除”,事实上,我使用数据连接向导构建了我的应用程序配置,这导致连接只应用于我的bin/debug文件夹中的数据库文件副本,其中包含10倍于10倍调用的所有更新alot@SyedaDataAdapter上没有DeleteDataRow[]方法我也有同样的问题,一切似乎都很好,但数据库没有反映出变化。事实证明,在使用CommandBuilder之后没有UpdateCommand。
 /get only the rows you want
 DataRow[] result = employees_table.Select("ID ="+id); //id will be provided by you
 //Now do here data updation 
 adapter.delete(result);
 adapter.Update(employees_table);
MessageBox.Show(adapter.UpdateCommand.CommandText);