在插入期间在 c# 中捕获 sql 唯一约束违规的最佳方法

Best way to catch sql unique constraint violations in c# during inserts(在插入期间在 c# 中捕获 sql 唯一约束违规的最佳方法)
本文介绍了在插入期间在 c# 中捕获 sql 唯一约束违规的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 c# 中有一个循环插入到表中.很基本的东西.当违反唯一约束时抛出的异常对象是否有一些东西可以用来查看违规值是什么?

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 的代码拼凑在一起,可以找到它,但我想要一些可以用作更永久解决方案的东西.

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,特别是违反主键约束.通过查看抛出的异常的 number 属性,您可以从此异常中获取此特定错误.这个答案可能与您需要的有关:如何识别SQL Server 2008 错误代码中的主键重复?

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

这篇关于在插入期间在 c# 中捕获 sql 唯一约束违规的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)