如何捕捉SQLServer的超时异常 [英] How to catch SQLServer timeout exceptions
问题描述
我需要专门捕获SQL服务器超时异常,以便他们可以不同的方式处理。我知道我能赶上SQLException中,然后检查如果消息字符串包含超时,但不知道是否有更好的方法来做到这一点?
尝试
{
//一些code
}
赶上(SQLEXCEPTION前)
{
如果(ex.Message.Contains(超时))
{
//处理超时
}
其他
{
扔;
}
}
要检查是否有超时,我相信你检查ex.Number的价值。如果是-2,那么你有一个超时的情况。
-2是错误$ C $下超时,从DBNETLIB,MDAC的驱动程序,SQL Server返回。这可以通过下载反射,并期待下System.Data.SqlClient.TdsEnums的TIMEOUT_EXPIRED可见。
您code应改为:
如果(ex.Number == -2)
{
//处理超时
}
code证明失败:
尝试
{
SqlConnection的SQL =新的SqlConnection(@网络图书馆= DBMSSOCN;数据源= YourServer 1433;初始目录= YourDB;集成安全性= SSPI;);
sql.Open();
的SqlCommand CMD = sql.CreateCommand();
cmd.CommandText =DECLARE @i INT WHILE EXISTS(SELECT 1,从系统对象)首先,选择@i = 1 END;
cmd.ExecuteNonQuery(); //此行会超时。
cmd.Dispose();
sql.Close();
}
赶上(SQLEXCEPTION前)
{
如果(ex.Number == -2){
Console.WriteLine(超时发生了);
}
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;
}
}
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 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.
Your code would read:
if (ex.Number == -2)
{
//handle timeout
}
Code to demonstrate failure:
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屋!