如何知道实际的问题,这是因为抛出SQLException? [英] How to know actual problem because of which SqlException is thrown?

查看:172
本文介绍了如何知道实际的问题,这是因为抛出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#code,我们只有 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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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