SQLServer 시간 초과 예외를 포착하는 방법
다르게 처리 할 수 있도록 SQL Server 시간 초과 예외를 구체적으로 잡아야합니다. SqlException을 잡아서 메시지 문자열에 "Timeout"이 포함되어 있는지 확인할 수 있지만 더 좋은 방법이 있는지 궁금합니다.
try
{
//some code
}
catch (SqlException ex)
{
if (ex.Message.Contains("Timeout"))
{
//handle timeout
}
else
{
throw;
}
}
시간 초과를 확인하기 위해 ex.Number의 값을 확인한다고 생각합니다. -2이면 시간 종료 상황이 있습니다.
-2는 시간 초과에 대한 오류 코드이며 SQL Server 용 MDAC 드라이버 인 DBNETLIB에서 리턴됩니다. Reflector 를 다운로드 하고 TIMEOUT_EXPIRED에 대한 System.Data.SqlClient.TdsEnums를 보면 알 수 있습니다 .
코드는 다음과 같습니다.
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");
}
}
여기 : http://www.tech-archive.net/Archive/DotNet/microsoft.public.dotnet.framework.adonet/2006-10/msg00064.html
또한 Thomas Weingartner가 쓴 내용을 읽을 수 있습니다 .
시간 초과 : SqlException.Number == -2 (ADO.NET 오류 코드 임)
일반 네트워크 오류 : SqlException.Number == 11
교착 상태 : SqlException.Number == 1205 (SQL Server 오류 코드)
...
"일반 네트워크 오류"도 시간 초과 예외로 처리합니다. 업데이트 / 삽입 / 삭제 쿼리가 장시간 실행되는 트리거와 같은 드문 상황에서만 발생합니다.
C # 6으로 업데이트 :
try
{
// some code
}
catch (SqlException ex) when (ex.Number == -2) // -2 is a sql timeout
{
// handle timeout
}
매우 간단하고보기 좋습니다!
SqlException.ErrorCode 속성의 값은 무엇입니까? 당신은 그 일을 할 수 있습니까?
When having timeouts, it may be worth checking the code for -2146232060.
I would set this up as a static const in your data code.
참고URL : https://stackoverflow.com/questions/29664/how-to-catch-sqlserver-timeout-exceptions
'Programming' 카테고리의 다른 글
Java 파일에 jar 파일을 포함시키고 명령 프롬프트에서 컴파일하는 방법 (0) | 2020.07.27 |
---|---|
멤버 생성자 및 소멸자 호출 순서 (0) | 2020.07.27 |
비활성 조합원 및 정의되지 않은 동작에 액세스하고 있습니까? (0) | 2020.07.27 |
"당신은 의미합니까?"를 어떻게 구현합니까? (0) | 2020.07.27 |
자식 하위 디렉토리를 추출하고 하위 모듈을 만드는 방법은 무엇입니까? (0) | 2020.07.27 |