如何使用ado.net更新多行Sql表(c#) [英] How do I Update multiple rows of Sql table using ado.net(c#)

查看:108
本文介绍了如何使用ado.net更新多行Sql表(c#)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一个DatagridView。该场景是当我更改某些行的值并单击SaveButton时,数据库中的表将被更新。为此,我创建了一个对象列表并将所有DGV行放入此list(DGV的每一行都映射到一个对象)。然后在foreach循环中我读取这个列表并更新数据库中相关的表行。我知道这种方式性能较差,因为它多次连接到db。有没有办法轻松更新或插入多行?



there is a DatagridView.the scenario is when I change the value of some rows and click on SaveButton, the table in database will be updated.For doing this,I made a list of objects and put all rows of DGV into this list(every row of DGV is mapped to One object). then in a foreach loop I read this list and update the related row of table in database.I know this way has less performance because it connect to db multiple times.Is there any way to Update or insert multiple rows easily?

List<Person> lst = PutRowsOfDGVIntoList();
if (lst != null && lst.Count != 0)
{

    foreach (var person in lst)
    {
      if (!pda.ifExistPerson())//if current row don't exist in Db insert new person else update
      {
         if (!pda.InsertPerson(person))//insert
          throw new Exception();

      }
      else
      {
         if (!pda.UpdatePerson(person))//update
                    throw new Exception();
      }
   }
}

推荐答案

如果您使用DataAdapter并绑定您的数据,然后全部为您处理: http:// msdn。 microsoft.com/en-us/library/fbk67b6z(v=vs.90).aspx [ ^ ]



该链接包含完成所有操作的示例代码!
If you use a DataAdapter and bind your data, then it is all handled for you: http://msdn.microsoft.com/en-us/library/fbk67b6z(v=vs.90).aspx[^]

The link includes sample code to do it all!


您的方法有多种替代方案 - 尤其是在编写过程开始时只连接一次数据库,完成时断开连接(每个对象不一次)



这是要尝试的事项列表 [ ^ ]
There are several alternatives to your approach - not least only connect to the database once at the beginning of your write process and disconnect when finished (not once per object)

Here is a list of things to try[^]


这篇关于如何使用ado.net更新多行Sql表(c#)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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