如何知道由于哪个 SqlException 被抛出而导致的实际问题?

How to know actual problem because of which SqlException is thrown?(如何知道由于哪个 SqlException 被抛出而导致的实际问题?)
本文介绍了如何知道由于哪个 SqlException 被抛出而导致的实际问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想以不同的方式处理不同的问题,同时进行数据库操作.

I want to handle different problems, while doing database operations, differently.

例如由于错误的数据库凭据或网络问题,操作可能会失败.或者它可能因为查询不正确而失败(如果在int类型列中传递字符串值)

e.g. The operation may fail because of wrong database credentials or due to network problem. Or it may fail because the query is not correct (if string value is being passed in the int type column)

在我的 C# 代码中,我们只有 SqlException,它具有 SqlErrors 的集合.但是有许多严重级别.

In my C# code, we only have SqlException which has collection of SqlErrors. However there are many severity levels.

如何轻松确定 SqlException 的原因?我如何确定异常是由于连接问题或身份验证失败还是由于查询问题.

How can i easily identify the cause of the SqlException ? How can i determine the exception is because of the connectivity problem or authentication failure or because of the problem with the query.

我使用的是 SQL Server 2005.

I am using SQL Server 2005.

推荐答案

试试这样,这将帮助你处理不同的情况.

Try something like this, this will help you in handling different conditions.

像这样使用 try catch 块:

use a try catch block like this:

try    
{
  ...
  ...
}
catch (SqlException ex)
{
  switch (ex.Number) 
    { 
        case 4060: // Invalid Database 
                  ....
                  break;

        case 18456: // Login Failed 

                  ....

                  break;

        case 547: // ForeignKey Violation 

                  ....

                  break;

        case 2627: 
                // Unique Index/ Primary key Violation/ Constriant Violation 

                  ....

                  break;

        case 2601: // Unique Index/Constriant Violation 

                  ....

                  break;

        default: 

                  ....

                  break;    

       } 
}

这篇关于如何知道由于哪个 SqlException 被抛出而导致的实际问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

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

相关文档推荐

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子句?)