捕获的SQLException和处理 [英] SqlException catch and handling

查看:1153
本文介绍了捕获的SQLException和处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问:有没有更好的方式来处理的SQLException?

下面的示例依赖于跨preting消息中的文本。

例1:我有一个现有的尝试catch来处理,如果表不存在结果
忽略的事实是,如果表摆在首位存在我可以检查。

 尝试
{
    // code
}
赶上(SQLEXCEPTION sqlEx)
{
        如果(sqlEx.Message.StartsWith(无效的对象名称))
        {
            // code
        }
        其他
            扔;
}

为Eg2:没有尝试捕捉显示重复键异常

 如果(sqlEx.Message.StartsWith(不能在对象中插入重复键行))

解决方案:我SqlExceptionHelper的开始

  //  - 看到错误消息列表:SELECT * FROM sys.messages那里LANGUAGE_ID = 1033 ORDER BY与Message_ID
公共静态类SqlExceptionHelper
{
    // - 规则:添加错误信息的数字顺序和preFIX方法上面的数字    // - 208:无效的对象名称%1!'。
    公共静态布尔IsInvalidObjectName(SQLEXCEPTION性行为)
    {回报(sex.Number == 208); }    // - 2601:不能在对象插入重复键行%1!'具有唯一索引'%1!'。重复的键值为%2!。
    公共静态布尔IsDuplicateKey(SQLEXCEPTION性行为)
    {回报(sex.Number == 2601); }
}


解决方案

SQLException中具有的 Number属性,你可以检查。重复错误的数量是2601。

 赶上(SQLEXCEPTION E)
{
   开关(e.Number)
   {
      案例2601:
         // 做一点事。
         打破;
      默认:
         扔;
   }
 }

要得到你服务器的所有SQL错误的列表,试试这个:

  SELECT * FROM的sysmessages

更新

这现在可以简化在C#6.0

 赶上(SQLEXCEPTION e)在(e.Number == 2601)
{
   // 做一点事。
}

Q: Is there a better way to handle SqlExceptions?

The below examples rely on interpreting the text in the message.

Eg1: I have an existing try catch to handle if a table does not exist.
Ignore the fact that I could check if the table exists in the first place.

try
{
    //code
}
catch(SqlException sqlEx)
{
        if (sqlEx.Message.StartsWith("Invalid object name"))
        {
            //code
        }
        else
            throw;
}

Eg2: without the try catch showing duplicate key exception

if (sqlEx.Message.StartsWith("Cannot insert duplicate key row in object"))

Solution: The start of my SqlExceptionHelper

//-- to see list of error messages: select * from sys.messages where language_id = 1033 order by message_id
public static class SqlExceptionHelper
{
    //-- rule: Add error messages in numeric order and prefix the number above the method

    //-- 208: Invalid object name '%.*ls'.
    public static bool IsInvalidObjectName(SqlException sex)
    { return (sex.Number == 208); }

    //-- 2601: Cannot insert duplicate key row in object '%.*ls' with unique index '%.*ls'. The duplicate key value is %ls.
    public static bool IsDuplicateKey(SqlException sex)
    { return (sex.Number == 2601); }
}

解决方案

The SqlException has a Number property that you can check. For duplicate error the number is 2601.

catch (SqlException e)
{
   switch (e.Number)
   {
      case 2601:
         // Do something.
         break;
      default:
         throw;
   }
 }

To get a list of all SQL errors from you server, try this:

 SELECT * FROM sysmessages

Update

This can now be simplified in C# 6.0

catch (SqlException e) when (e.Number == 2601)
{
   // Do something.
}

这篇关于捕获的SQLException和处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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