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

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

问题描述

我需要专门捕获SQL Server超时异常,以便它们的处理方式不同。我知道我可以抓住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是DBNETLIB(SQL Server的MDAC驱动程序)返回的超时错误代码。这可以通过下载反射器并查看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天全站免登陆