How to know actual problem because of which SqlException is thrown?

江枫思渺然 提交于 2019-12-17 14:02:09

问题


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

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)

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

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.

I am using SQL Server 2005.


回答1:


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

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;    

       } 
}



回答2:


SQLException exposes the property Class which should give you the severity level.

More information here.



来源:https://stackoverflow.com/questions/4825365/how-to-know-actual-problem-because-of-which-sqlexception-is-thrown

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!