为什么这个foreach不起作用? [英] Why this foreach dont work?

查看:104
本文介绍了为什么这个foreach不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

即时通讯在数据集中使用foreach来更新sql服务器,如果元素alredy存在则只捕获错误并尝试使用下一个。我的表有13个元素,这个foreach给第一个元素的错误13次:



im triying use foreach in a dataset to update a sql server, if the element alredy exist just catch the error and try with the next. My table have 13 elements and this foreach is giving the error of the first element 13 times :

System.Data.SqlClient.SqlException (0x80131904): Violation of PRIMARY KEY constraint ;PK_share1;. Cannot insert duplicate key in object ;dbo.share1&. The duplicate key value is (4008).




if (changes != null)
                    {
                        foreach (DataTable table in changes.Tables)
                        {
                            foreach (DataRow dr in table.Rows)
                            {
                                try
                                {
                                    adapter.Update(changes);
                                    
                                }

                                catch (Exception ex)
                                {
                                    Console.WriteLine(ex.ToString());
                                   
                                }

                              
                            }
                        }
                    }

推荐答案

你不是真的在这里进行循环更新,而是在你的DataAdapter上为每个表中的每一行调用Update ...

问题是DataAdapter.Update - 内部 - 运行状态为插入,更新或删除的所有行...

请在此处阅读:https://msdn.microsoft的.com / EN-US /库/ system.data.common.dataadapter.update(v = vs.110).ASPX CS-保存琅= 1&安培; CS琅= CSHARP#代码片断-1 [ ^ ]
You are not really do an in-loop update here, but rather call Update on your DataAdapter for each row in each table...
The problem is that DataAdapter.Update - internally - runs over all the rows that have a status of inserted, updated or deleted...
Please read here: https://msdn.microsoft.com/en-us/library/system.data.common.dataadapter.update(v=vs.110).aspx?cs-save-lang=1&cs-lang=csharp#code-snippet-1[^]


我的解决方案正是我想要的:



my solution for do exactly what i want:

adapter.ContinueUpdateOnError = true;
                  adapter.Update(changes);


这篇关于为什么这个foreach不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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