且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-08-23 15:22:28

看看类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 == ...)
{
    ...
}