如何在C#中处理特定的SQL异常(例如,违反唯一约束)? [英] How do I handle specific SQL exceptions (for example, a unique constraint violation) in C#?

查看:537
本文介绍了如何在C#中处理特定的SQL异常(例如,违反唯一约束)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题是如何在c#中处理sql异常,是否仍然需要检查从数据访问层抛出的sql异常类型?例如,如果db抛出唯一约束异常或外键异常,是否有任何方法可以从c#中捕获它?您对这些数据库异常使用的异常处理模式是什么?

my question is how to handle sql exception in c#, is there anyway to check what kind of the sql exception throws from data access layer? For example, if db throws an unique constraint exception, or foreign key exception, is there any way to catch it from c#? what's the exception handling pattern you are using for these db exception?

推荐答案

看看类SqlException 的文档,尤其是在其属性 SqlException.Number ,例如,应该允许您识别发生哪种类型的SqlException(唯一约束,外键等)。

Have a look at the documentation of the SqlException class, in particular, at its properties: SqlException.Number, for example, should allow you to identify which type of SqlException (unique constraint, foreign key, ...) occurred.

您可以使用过滤的异常来捕获特定错误。 VB.NET:

You can use filtered exceptions to catch specific errors. VB.NET:

Try
    ...
Catch ex as SqlException When ex.Number = ...
    ...
Catch ex as SqlException When ex.Number = ...
    ...
End Try

C#(版本6及更高版本):

C# (Version 6 and above):

try
{
    ...
}
catch (SqlException ex) when (ex.Number == ...)
{
    ...
}
catch (SqlException ex) when (ex.Number == ...)
{
    ...
}

这篇关于如何在C#中处理特定的SQL异常(例如,违反唯一约束)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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