如何捕获 SQLServer 超时异常 [英] How to catch SQLServer timeout exceptions

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

问题描述

我需要专门捕获 SQL 服务器超时异常,以便可以不同地处理它们.我知道我可以捕获 SqlException,然后检查消息字符串是否包含超时",但想知道是否有更好的方法来做到这一点?

I need to specifically catch SQL server timeout exceptions so that they can be handled differently. I know I could catch the SqlException and then check if the message string Contains "Timeout" but was wondering if there is a better way to do it?

try
{
    //some code
}
catch (SqlException ex)
{

    if (ex.Message.Contains("Timeout"))
    {
         //handle timeout
    }
    else
    {
         throw;
    }
}

推荐答案

要检查超时,我相信您检查 ex.Number 的值.如果它是-2,那么你有一个超时情况.

To check for a timeout, I believe you check the value of ex.Number. If it is -2, then you have a timeout situation.

-2 是超时的错误代码,从 SQL Server 的 MDAC 驱动程序 DBNETLIB 返回.这可以通过下载 Reflector 并在 System.Data.SqlClient.TdsEnums 下查看来查看对于 TIMEOUT_EXPIRED.

-2 is the error code for timeout, returned from DBNETLIB, the MDAC driver for SQL Server. This can be seen by downloading Reflector, and looking under System.Data.SqlClient.TdsEnums for TIMEOUT_EXPIRED.

您的代码将显示为:

if (ex.Number == -2)
{
     //handle timeout
}

证明失败的代码:

try
{
    SqlConnection sql = new SqlConnection(@"Network Library=DBMSSOCN;Data Source=YourServer,1433;Initial Catalog=YourDB;Integrated Security=SSPI;");
    sql.Open();

    SqlCommand cmd = sql.CreateCommand();
    cmd.CommandText = "DECLARE @i int WHILE EXISTS (SELECT 1 from sysobjects) BEGIN SELECT @i = 1 END";
    cmd.ExecuteNonQuery(); // This line will timeout.

    cmd.Dispose();
    sql.Close();
}
catch (SqlException ex)
{
    if (ex.Number == -2) {
        Console.WriteLine ("Timeout occurred");
    }
}

这篇关于如何捕获 SQLServer 超时异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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