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

后端 未结 2 690
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-03 23:14

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 networ

2条回答
  •  一整个雨季
    2020-12-03 23:30

    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;    
    
           } 
    }
    

提交回复
热议问题