2014-04-17 2 views
0

여기 내 코드입니다..net의 SQL Server 연결

public Dataset ReturnDataset() 
{ 
SqlConnection con = new SqlConnection(Proper connectionstring); 
SqlCommand cmd = new SqlCommand(spname,con); 
Dataset ds = new Dataset(); 
try 
{ 
con.Open(); 
cmd.CommandType = CommandType.StoreProcedure; 
SqlDataAdapter da = new SqlDataAdapter(cmd); 
da.Fill(ds,table); 
return ds; 
} 
catch (TimeoutException Ex) 
      { 
       con.Close(); 
       if (Ex.Message.Contains("Timeout expired")) 
       { 
        ds = null; 
        return ds; 
       } 
       else 
       { 
        throw; 
       } 
      } 
      catch (Exception) 
      { 
       throw; 
      } 

오류 발생 여부 만약 내가 연결을 종료하는 마지막 절을 작성해야합니까? 첫 번째 시도 블록에서 내가 연결을 종료 한 후 나는 두 번째 블록에서 동일 할 필요가 exception.Does을 던져? 이미있는 경우 무슨 일이 일어날 지 닫힌 연결 및 다시 닫으려고?

+0

마지막으로 블록 연결을 닫습니다! –

+0

모든 도움을 주셔서 감사합니다. –

답변

1

다음과 같이 시도 캐치의 finally 부분에 연결을 닫거나 using 한 Statment를 사용하여 .NET 알아서 할 수 있도록 항상 좋은 생각이다 :

try{ 
} 
catch{ 
} 
finally{ 
conn.close(); 
} 

를 사용하거나 using :

using (SqlConnection connection = new SqlConnection(connectionString)) 
{ 
} 

오류가 발생해도 닫을 수 있습니다. 당신이 열려있는 경우 확인할 수 닫기 전에 연결의 상태에 대한 걱정과 finally에 닫습니다 경우

if (conn != null && conn.State == ConnectionState.Open) 
{ 
    conn.close(); 
} 
1

반드시 필요한 그렇지 않은 경우 나는 구조화 catch 폭포를 만들 마십시오.

필요하다면 더 일반적인 예외보다 더 구체적인 예외에서 항상 catch 캐스케이드를 정의하려고합니다.

난 항상 finally 블록의 모든 정리 논리를 넣어 :

SqlConnection con = new SqlConnection(Proper connectionstring); 
SqlCommand cmd = new SqlCommand(spname,con); 
Dataset ds = new Dataset(); 
try 
{ 
    con.Open(); 
    cmd.CommandType = CommandType.StoreProcedure; 
    SqlDataAdapter da = new SqlDataAdapter(cmd); 
    da.Fill(ds,table); 
    return ds; 
} 
catch(TimeoutException toEx) 
{ 
    //manage or log specific exception 
} 
catch(Exception ex) 
{ 
    //manage or log generic exception 
} 
finally 
{ 
    //cleanup 
    con.Close(); 
    ds = null; 
} 
1

더 나은 옵션을 사용하면

public Dataset ReturnDataset() 
{ 
    using (SqlConnection con = new SqlConnection(connectionstring)) 
    using (SqlCommand cmd = new SqlCommand(spname,con)) 
    { 
    Dataset ds = new Dataset(); 
    try 
    { 
     con.Open(); 
     cmd.CommandType = CommandType.StoreProcedure; 
     SqlDataAdapter da = new SqlDataAdapter(cmd); 
     da.Fill(ds,table); 
    } 
    catch (TimeoutException Ex) 
    { 
     ds = null; 
    } 
    return ds; 
    } 
} 
1

내가 다시 것이기 폐기/폐쇄를 수행하는 using 키워드를 사용하는 것입니다 귀하의 코드는 다음과 같습니다 :

public DataSet ReturnDataset() 
{ 
    // initialize return value 
    DataSet result = null; 

    // put SqlConnection and SqlCommand into using() { ....} blocks to ensure proper disposal  
    using (SqlConnection con = new SqlConnection(Proper connectionstring)) 
    using (SqlCommand cmd = new SqlCommand(spname, con)) 
    { 
     result = new DataSet(); 

     try 
     { 
      con.Open(); 

      // you had a typo: it's a StoredProcedure - not a StoreProcedure 
      cmd.CommandType = CommandType.StoredProcedure; 

      SqlDataAdapter da = new SqlDataAdapter(cmd); 
      da.Fill(result, table); 

      con.Close(); 
     } 
     catch (TimeoutException Ex) 
     { 
      if (Ex.Message.Contains("Timeout expired")) 
      { 
       result = null; 
      } 
      else 
      { 
       throw; 
      } 
     } 
    } 

    // return the result - null if an error happened, a valid DataSet otherwise 
    return result; 
} 

포인트 나는 개선 :

  • 는 매우 당신이 아무것도하지 않는 예외에
  • 제거 불필요 "캐치"끝에서 한 번만 반환, 처음에 가능한 반환 값을 선언 -> 그냥
  • 을 일어나게을
1

왜 당신이 적절한 폐쇄 및 일회용 객체의 처분을 보장 using 문을 사용하지 않는 적절하고 신속한 처리를 위해 using(...) { ... } 블록으로 SqlConnectionSqlCommand을 넣어? 나는 당신이 단지 그들에게하자 거품을 위로하고,이 수준에서 예외를 잡을 필요가 없습니다 생각, 상위 여기

할 수 있습니다 단순히

public Dataset ReturnDataset() 
{ 
    Dataset ds = new Dataset(); 
    using(SqlConnection con = new SqlConnection(Proper connectionstring)) 
    using(SqlCommand cmd = new SqlCommand(spname,con)) 
    { 
     con.Open(); 
     cmd.CommandType = CommandType.StoreProcedure; 
     using(SqlDataAdapter da = new SqlDataAdapter(cmd)) 
     { 
      da.Fill(ds,table); 
     } 
    } 
    return ds; 
} 

이 코드는 만약에 그들 중 돌봐를 필요한 경우 예외가 발생하면 데이터 집합이 반환되지 않고 로컬 변수가 될 때 가비지 수집 대상이됩니다.