처음으로 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(" "));
}
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을 관리하는 가장 좋은 방법은 무엇입니까? 감사합니다.
에 쿼리를 실행 SQL 데이터베이스에서 수를 얻으려면, 완료되면 연결을 처분하십시오. IT는 지금 그렇게 보이지 않습니다. – recursive
'finally'블록에 있습니다. –
하지만 루프에 다른 sqlconnection 객체를 만드는 것이 맞습니까? 연결을 끊으면 그걸 처리해야합니까? –