2010-06-20 2 views
10

using 문을 사용하여 가능합니까? C# SQL?C# using 문, SQL 및 SqlConnection

private static void CreateCommand(string queryString, 
    string connectionString) 
{ 
    using (SqlConnection connection = new SqlConnection(
       connectionString)) 
    { 
     SqlCommand command = new SqlCommand(queryString, connection); 
     command.Connection.Open(); 
     command.ExecuteNonQuery(); 
    } 
} 

연결을 여는 중 오류가 발생하면 어떻게해야합니까?

using 문을 시도하고있다 마지막으로
없음 캐치

그래서 캐치 오류를 열고 연결을 잡을 것이다 사용하는 괄호 밖에 잡으면?

그렇지 않은 경우 위의 using 문을 사용하여 구현하는 방법은 무엇입니까?

+0

TIAS (.........) – zerkms

답변

13

그것은 C#에서 그렇게 할 (나는 또한 그 코드가 정확히 MSDN http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executenonquery.aspx에 표시됩니다 참조) 가능합니다. 당신이 방어 및 프로덕션 환경에서 문제 해결을 도움이 될 잠재적 인 예외를 기록, 예를 들어 일해야하는 경우, 당신은이 방법을 수행 할 수 있습니다

private static void CreateCommand(string queryString, 
string connectionString) 
{ 
    using (SqlConnection connection = new SqlConnection(
      connectionString)) 
    { 
     try 
     { 
      SqlCommand command = new SqlCommand(queryString, connection); 
      command.Connection.Open(); 
      command.ExecuteNonQuery(); 
     } 
     catch (InvalidOperationException) 
     { 
      //log and/or rethrow or ignore 
     } 
     catch (SqlException) 
     { 
      //log and/or rethrow or ignore 
     } 
     catch (ArgumentException) 
     { 
      //log and/or rethrow or ignore 
     } 
    } 
} 
+0

고맙습니다, 그리고 그 정확한 msdn 코드, 학습 오전 ... – user287745

5

오류를 잡으려면 try - catch 블록의 모든 것을 감쌀 필요가 있습니다. using 블록은 단순히 관리되지 않는 리소스가 삭제되었는지 확인하고 예외를 처리 할 수 ​​없도록합니다.

또한 SqlCommandIDisposable을 구현하므로 using 블록에도 넣는 것이 좋습니다.

1

예, 당신은 try 블록에서 using 블록을 넣을 수 있습니다, 다음과 같은 catchtry 블록에 관련된 오류를 잡을 것입니다.

2

그냥 명시 적으로 그것을 쓰기 :

SqlConnection connection = new SqlConnection(connectionString); 
try 
{ 
    using (SqlCommand command = new SqlCommand(queryString, connection)) 
    { 
     command.Connection.Open(); 
     command.ExecuteNonQuery(); 
    } 
} 
catch (Exception e) 
{ 
    // ...handle, rethrow. Also, you might want to catch 
    // more specific exceptions... 
} 
finally 
{ 
    connection.Close(); 
} 
+0

어떻게 그렇게 좋습니까? using 블록에서 SqlConnection을 사용하면 호출이 끝납니다. –

+0

일부 논리 문제가 맞습니까? 캐치가 발생한 다음 잘 처리되어 결국 작동합니다. 오류가 발생하지 않으면 어떻게해야합니까? connection opened-work done-using은 연결을 암시 적으로 닫은 다음 마지막으로 닫힌 연결을 닫으려고 시도합니다! 오류 ..... 오른쪽? – user287745

+0

아니요. 두 경우 모두 ("using"을 사용하고 명시 적으로 작성) finally 블록이 호출됩니다. SqlConnection.Close()가 호출됩니다. –

0

이 분야에 대한 데이터베이스에 고유 인덱스를 추가하고 오류를 잡아 .

각 행에 대해 SQL 연결을 다시 인스턴스화하지 마십시오. 연결 열기 및 닫기는 자원 집약적입니다. 다음과 같이 시도하십시오.

protected void btn_insert_Click(object sender, EventArgs e) 
{ 
    string connStr = "your connection string"; 
    SqlCommand cmd; 

    using (SqlConnection con = new SqlConnection(connStr)) 
    { 
     con.Open(); 
     foreach (GridViewRow g1 in GridView1.Rows) 
     { 
      try 
      { 
       cmd = new SqlCommand("command text", con); 
       cmd.ExecuteNonQuery(); 
      } 
      catch (SqlException sqlEx) 
      { 
       //Ignore the relevant Sql exception for violating a sql unique index 
      } 
     } 
    } 
}