c# - 如何在 C# 中处理特定的 SQL 异常(例如,违反唯一约束)?

标签 c# exception

我的问题是如何在 C# 中处理 sql 异常,有没有办法检查从数据访问层抛出的 sql 异常类型?例如,如果db抛出一个唯一约束异常,或者外键异常,有没有办法从c#中捕获它?您对这些数据库异常使用的异常处理模式是什么?

最佳答案

看看 documentation of the SqlException类,特别是在其 properties : SqlException.Number ,例如,应该允许您识别发生了哪种类型的 SqlException(唯一约束、外键、...)。

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

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

C#(版本 6 及以上):

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

关于c# - 如何在 C# 中处理特定的 SQL 异常(例如,违反唯一约束)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1666887/

相关文章:

c# - c# 中的时间跨度交集

c# - 分页错误 :The method 'Skip' is only supported for sorted input in LINQ to Entities. 方法 'OrderBy' 必须在方法 'Skip' 之前调用

使用 JavaScript 在 MVC 中调用 C# 函数

c# - 找到多个相同类型的自定义属性。时间:2019-03-17 标签:c#botframework中的异常

java - 为什么会出现这个异常?

c++ - 在 C++ 中抛出超出范围的异常

c# - 如何使用 for 循环为多个类属性(如项目列表)赋值?

java.lang.ClassNotFoundException :com. mysql.jdbc.Driver 异常

java - 如何在 Clojure 中捕获多个异常?

android - 获取 "java.lang.IllegalArgumentException: Unknown URL content in"Android