如何捕获特定的SqlException错误? [英] How to catch a specific SqlException error?

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

问题描述

问:是否有更好的方法来处理SqlException?

Q: Is there a better way to handle SqlExceptions?

下面的示例依赖于解释消息中的文本。

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

Eg1::如果表不存在,我有一个现有的try catch来处理。

忽略我可以检查表是否首先存在的事实。

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 :没有try catch显示重复的键

Eg2: without the try catch showing duplicate key exception

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

解决方案:我的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); }
}


推荐答案

SqlException具有<您可以检查的href = http://msdn.microsoft.com/zh-cn/library/system.data.sqlclient.sqlexception.number.aspx rel = noreferrer>数字属性。对于重复错误,数字为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;
   }
 }

从服务器获取所有SQL错误的列表,请尝试以下操作:

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

 SELECT * FROM sysmessages

更新

现在可以在C#6.0中简化

This can now be simplified in C# 6.0

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

这篇关于如何捕获特定的SqlException错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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