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

后端 未结 2 688
佛祖请我去吃肉
佛祖请我去吃肉 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;    
    
           } 
    }
    
    0 讨论(0)
  • 2020-12-03 23:39

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

    More information here.

    0 讨论(0)
提交回复
热议问题