如何将数据表中的数据保存回数据库中? [英] How to save the data in a datatable back into the database?

查看:137
本文介绍了如何将数据表中的数据保存回数据库中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经用与我的sqlcommand和sqlconnection关联的sqladapter填充了数据表.我已经通过绑定到其列之一的文本框更改了其内容.我想将其中的数据保存回数据库中,并按以下步骤进行操作,但不起作用:

I have filled my datatable with my sqladapter associated with my sqlcommand and sqlconnection. I have changed its contents by a textbox bound to one of its column. I want to save the data in it back into the database and I have done as the following but it doesn''t work:

mydatatable.Merge(mydatatable.GetChanges());
mydatatable.AcceptChanges();
mydataadapter.Update(mydatatable);


当然,它不会检查新更改中是否有任何错误,但是假设没有任何错误.
您可以更正我的代码吗?为什么不起作用?如果使用诸如datagrid之类的方法,我可以使用DataAdapter.Update方法轻松地更新数据.
非常感谢!


Of course, it doesn''t check if there is any errors in the new changes but suppose there''s not any error.
Could you please correct my code? Why doesn''t it work? If using such as a datagrid, I can easily update the data using DataAdapter.Update method.
Thank you so much!

推荐答案

1)将mydatatable中的更改合并到完全相同的mydatatable中是没有意义的,不会有任何变化,因此不是错误,只是浪费CPU周期.所以我建议您删除mydatatable.Merge(mydatatable.GetChanges());

2)mydatatable.AcceptChanges();调用AcceptChanges会将DataTable中所有行的状态设置为不变".因此,在此调用之后,无需更改即可提交到数据库.
删除mydatatable.AcceptChanges();并假定您已经设置了SqlDataAdapter的UpdateCommand和InsertCommand或使用如何通过使用Visual C#.NET中的SqlDataAdapter对象更新SQL Server数据库 [
1) Merging changes from mydatatable into the very same mydatatable makes no sense, nothing will change, so it''s not an error, just a waste of CPU cycles. So I suggest you remove mydatatable.Merge(mydatatable.GetChanges());

2) mydatatable.AcceptChanges(); calling AcceptChanges will set the state of all rows in the DataTable to Unchanged. So after this call there are no changes to commit to a database.
Remove mydatatable.AcceptChanges(); and your code should work, assuming you''ve set the UpdateCommand and InsertCommand of the SqlDataAdapter either yourself or by using OleDbCommandBuilder[^]. If you haven''t then have a look at this:
How To Update a SQL Server Database by Using the SqlDataAdapter Object in Visual C# .NET[^]
It states it''s for SQL Server but that''s just a matter of difference in the SQLs the code is the same no matter which database you use.


这篇关于如何将数据表中的数据保存回数据库中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆