How to catch SQLServer timeout exceptions
我需要专门捕获SQL Server超时异常,以便以不同的方式处理它们。我知道我可以捕获sqlException,然后检查消息字符串是否包含"timeout",但我想知道是否有更好的方法来实现它?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | try { //some code } catch (SqlException ex) { if (ex.Message.Contains("Timeout")) { //handle timeout } else { throw; } } |
为了检查超时,我相信您检查了ex.number的值。如果是-2,则说明出现了超时情况。
-2是超时的错误代码,从DBNetLib返回,DBNetLib是SQL Server的MDAC驱动程序。这可以通过下载reflector并在system.data.sqlclient.tdsenums下查找超时值来查看。
您的代码将显示:
1 2 3 4 | if (ex.Number == -2) { //handle timeout } |
演示失败的代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | 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"); } } |
网址:http://www.tech-archive.net/archive/dotnet/microsoft.public.dotnet.framework.adonet/2006-10/msg00064.html你也可以读到托马斯·温加特纳写的:
Timeout: SqlException.Number == -2 (This is an ADO.NET error code)
General Network Error: SqlException.Number == 11
Deadlock: SqlException.Number == 1205 (This is an SQL Server error code)
…
We handle the"General Network Error" as a timeout exception too. It only occurs under rare circumstances e.g. when your update/insert/delete query will raise a long running trigger.
C 6更新:
1 2 3 4 5 6 7 8 | try { // some code } catch (SqlException ex) when (ex.Number == -2) // -2 is a sql timeout { // handle timeout } |
很简单很好看!!
sqlException.ErrorCode属性的值是什么?你能用它吗?
超时时,可能需要检查-2146232060的代码。
我会在您的数据代码中将其设置为静态常量。