2013-03-27 2 views
1

처음으로 stackoverflow에. WebForm 페이지에서 SqlConnection을 관리하는 방법을 배우고 있으며이를 수행하는 데 가장 좋은 방법을 찾고 싶습니다. 필자의 경우 루프가 있으며 루프의 모든 반복에 대해 새 SqlConnection을 설정하지 않으면 오류없이 코드를 실행할 수있는 방법이 없습니다 (오류는 판독기가 닫힐 때 읽는 오류입니다).). 그래서 PageLoad 방법이 선언 :C# 루프 내에서 SqlConnection

private SqlConnection con; 
protected void Page_Load(object sender, EventArgs e) 
{ 
    con = new SqlConnection(connectionString); 
} 

그럼이 있습니다

내가 "접점"전화 while 루프에서 buildParent에서
private int conta(int padre) 
{ 
    string SQL = "SELECT * FROM categories WHERE [email protected]"; 
    SqlCommand cd = new SqlCommand(SQL, con); 
    cd.Parameters.AddWithValue("@idpadre", padre); 
    int sub=0; 
    try 
    {     
     if ((con.State & ConnectionState.Open) <= 0) 
     { 
      con.Open(); 
     } 

     using (SqlDataReader reader = cd.ExecuteReader()) 
     { 
      while (reader.Read()) 
      { 
       sub++; 
      } 
     } 
    } 
    catch (Exception err) 
    { 
     lbl.Text = "Errore conta!"; 
     lbl.Text += err.Message; 
    } 
    finally 
    { 
     con.Close(); 

    } 
    return sub; 
} 

protected void buildParent(int padre, int level) 
{ 
    StringBuilder sb = new StringBuilder(); 
    sb.Append(" "); 
    for (int i = 0; i < level; i++) 
    { 
     sb.Append(HttpUtility.HtmlDecode("&nbsp;&nbsp;&nbsp;&nbsp;")); 
    } 
    sb.Append("|--"); 
    selectSQL = "SELECT * FROM categories WHERE [email protected]"; 
    SqlConnection cn = new SqlConnection(connectionString); 
    cmd = new SqlCommand(selectSQL, cn); 
    cmd.Parameters.AddWithValue("@idpadre", padre); 

    try 
    { 
     cn.Open(); 

     using (SqlDataReader read = cmd.ExecuteReader()) 
     { 
      while (read.Read()) 
      { 

       dlParent.Items.Add(new ListItem { Text = sb.ToString() + read["cat"].ToString(), Value = read["idcat"].ToString() }); 
       int sub = conta(Convert.ToInt32(read["idcat"])); 
       //int sub = 0; 
       if (sub > 0) 
       { 
        buildParent(Convert.ToInt32(read["idcat"]), level + 1); 
       } 

      } 
      read.Close(); 
     } 

    } 
    catch (Exception err) 
    { 
     lbl.Text = "Errore buildParent!"; 
     lbl.Text += err.Message; 
    } 
    finally 
    { 
     cn.Close(); 
     if (s != null) 
     { 
      if (!this.IsPostBack) 
      { 
       buildPage(); 
       buildLang(); 
       buildImage(); 
      } 
     } 
    } 
} 

,하지만 같은도록 SqlConnection을 사용하는 경우 (사기꾼) 두 가지 방법으로 나는 독자가 가까울 때 읽으려는 시도에 대해 오류가있다. 웹 서버의 연결 풀, 특히 최대 연결 도달 범위와 관련하여 걱정됩니다. 그래서, 내가 어디서 잘못 되었습니까? SqlConnection을 관리하는 가장 좋은 방법은 무엇입니까? 감사합니다.

답변

4

최대한 늦게 연결을 열면 가능한 한 빨리 처분합니다. 에서 연결 회수에 대한 조치를 취하십시오.

나는 보통 내 코드를 같이 쓰기 :

using (var conn = new SqlConnection(connectionString)) 
using (var cmd = new SqlCommand(commandToRun, conn)) 
{ 
    cmd.Parameters.AddRange(new[] 
     { 
      new SqlParameter("myParam", "myvalue"), 
      new SqlParameter("myParam", "myvalue") 
     }); 

    conn.Open(); // opened as late as possible 
    using (SqlDataReader reader = cd.ExecuteReader()) 
    { 
     while (reader.Read()) 
     { 
      // do stuff. 
     } 
    } 
} // disposed here. 

참고 : 당신은 더 나은

SELECT count(*) FROM categories WHERE [email protected] 

을 사용하고 또한 ExecuteScalar()

+0

에 쿼리를 실행 SQL 데이터베이스에서 수를 얻으려면, 완료되면 연결을 처분하십시오. IT는 지금 그렇게 보이지 않습니다. – recursive

+0

'finally'블록에 있습니다. –

+0

하지만 루프에 다른 sqlconnection 객체를 만드는 것이 맞습니까? 연결을 끊으면 그걸 처리해야합니까? –

관련 문제