赶上SQL唯一约束冲突在C#中插入的最佳方法 [英] Best way to catch sql unique constraint violations in c# during inserts

查看:179
本文介绍了赶上SQL唯一约束冲突在C#中插入的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在C#中循环插入到表中。 pretty的基本的东西。有什么insdie多数民众赞成时,抛出唯一约束违反,我可以用它来看看错误的值是异常对象?

I have a loop in c# that inserts into a table. pretty basic stuff. Is there something insdie the exception object that's thrown when a unique constraint is violated that i can use to see what the offending value is?

或者是有没有办法给它的SQL返回?我有一系列的文件,其数据即时加载到表中,我绑扎我的头试图找到的欺骗。

Or is there a way to return it in the sql? i have a series of files whose data im loading into tables and i'm banding my head trying to find the dupe.

我知道我可以拼凑的东西纯粹是基于IO在code,可以找到它,但我想要的东西,我可以作为一个长期的解决办法使用。

I know I could slap together something purely IO-based in code that can find it but I'd like something I could use as a more permanent solution.

推荐答案

您正在寻找的是一个SQLEXCEPTION,主键约束专门的侵犯。您可以通过查看抛出的异常的数量属性来获取此特定错误出此异常。这个答案很可能是有关你所需要的: <一href="http://stackoverflow.com/questions/15217711/how-to-identify-the-primary-key-duplication-from-a-sql-server-2008-error-$c$c">How从SQL Server 2008中的错误code标识的主键重复?

What you are looking for is a SqlException, specifically the violation of primary key constraints. You can get this specific error out of this exception by looking at the number property of the exception thrown. This answer is probably relevant to what you need: How to Identify the primary key duplication from a sql server 2008 error code?

总之,它看起来是这样的:

In summary, it looks like this:

// put this block in your loop
try
{
   // do your insert
}
catch(SqlException ex)
{
   // the exception alone won't tell you why it failed...
   if(ex.Number == 2627) // <-- but this will
   {
      //Violation of primary key. Handle Exception
   }
}

编辑:

这可能有点哈克,但你也可以只检查异常的消息组件。事情是这样的:

This may be a bit hacky, but you could also just inspect the message component of the exception. Something like this:

if (ex.Message.Contains("UniqueConstraint")) // do stuff

这篇关于赶上SQL唯一约束冲突在C#中插入的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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