Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
297 views
in Technique[技术] by (71.8m points)

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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;    

       } 
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...