code_junkie

How to catch SQLServer timeout exceptions

Nov 10th, 2011
137
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.72 KB | None | 0 0
  1. try
  2. {
  3. //some code
  4. }
  5. catch (SqlException ex)
  6. {
  7.  
  8. if (ex.Message.Contains("Timeout"))
  9. {
  10. //handle timeout
  11. }
  12. else
  13. {
  14. throw;
  15. }
  16. }
  17.  
  18. if (ex.Number == -2)
  19. {
  20. //handle timeout
  21. }
  22.  
  23. try
  24. {
  25. SqlConnection sql = new SqlConnection(@"Network Library=DBMSSOCN;Data Source=YourServer,1433;Initial Catalog=YourDB;Integrated Security=SSPI;");
  26. sql.Open();
  27.  
  28. SqlCommand cmd = sql.CreateCommand();
  29. cmd.CommandText = "DECLARE @i int WHILE EXISTS (SELECT 1 from sysobjects) BEGIN SELECT @i = 1 END";
  30. cmd.ExecuteNonQuery(); // This line will timeout.
  31.  
  32. cmd.Dispose();
  33. sql.Close();
  34. }
  35. catch (SqlException ex)
  36. {
  37. if (ex.Number == -2) {
  38. Console.WriteLine ("Timeout occurred");
  39. }
Add Comment
Please, Sign In to add comment