通过DataAdapter删除行
我已经初始化了一个 dataAdapter :
string sql = "SELECT * From localitati";
da1 = new System.Data.SqlClient.SqlDataAdapter(sql, con);
da1.Fill(ds1, "localitati");
这工作得很好。问题是当我尝试删除记录并更新数据库时。 我这样从数据集中删除一条记录:
ds1.Tables["localitati"].Rows.Remove(dRow);
这也很好用(已验证)。
问题是当我更新 DataAdapter 时,数据库没有被修改:
con.Open()
da1.Update(ds1, "localitati");
con.Close();
可能是什么问题?
I've initialized a dataAdapter :
string sql = "SELECT * From localitati";
da1 = new System.Data.SqlClient.SqlDataAdapter(sql, con);
da1.Fill(ds1, "localitati");
And this works just fine. The problem is when i try to delete a record and update the database.
I remove a record from the dataset as such :
ds1.Tables["localitati"].Rows.Remove(dRow);
And this works just fine as well(verified).
The problem is when i update the DataAdapter, the DataBase doesn't get modified :
con.Open()
da1.Update(ds1, "localitati");
con.Close();
What could be the problem ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
对我来说解决这个问题的方法是调用
DataRow
上的Delete
方法,而不是调用DataTable
上的Remove
方法。或者只是简单地
What fixed it for me was to call the
Delete
method on theDataRow
instead of theRemove
method on theDataTable
.or just simply
您需要确保已设置 da1.DeleteCommand - 这是将为 DataTable 中已删除的每一行触发的命令。例如,请参阅此 MSDN 参考。
You need to make sure you've set the da1.DeleteCommand - this is the command that will be fired for each row in the DataTable that has been deleted. See this MSDN reference for example.
尝试下面的代码
假设数据库没有抛出任何异常。
try below code
assuming that Database is not throwing any exception.
在您发布的代码中,仅为 DataAdapter 设置了 SelectCommand。
您可以使用以下代码为 da1 生成插入、更新和删除命令。
然而,CommandBuilder 只能用于相对简单的场景(详细信息)。至于其余的,建议编写自己的依赖于自定义命令文本/存储过程的命令。
如果仍然不起作用,您可以在服务器上启动 SQL Server Profiler 来跟踪执行 Update 方法时哪些命令访问了数据库。
In the code that you have posted only the SelectCommand is set for the DataAdapter.
You could use the following code to generate the Insert, Update and Delete commands for da1.
The CommandBuilder however should be used only for relatively simple scenarios (details). For he rest is recommended to write your own commands that rely on custom command texts/stored procedures.
If it still doesn't work, you could start a SQL Server Profiler on the server to trace what command gets to the database when you execute the Update method.