スタックオーバーフローで初めて。WebForm ページで SqlConnection を管理する方法を学んでおり、それを行うためのベスト プラクティスに到達したいと考えています。私の特定のケースでは、ループがあり、ループの反復ごとに新しい SqlConnection を設定しないと、エラーなしでコードを実行する方法がありません (エラーは、リーダーが閉じているときに読み取ろうとする試みに関するものです) . したがって、これを PageLoad メソッドで宣言します。
private SqlConnection con;
protected void Page_Load(object sender, EventArgs e)
{
con = new SqlConnection(connectionString);
}
それから私はこれを持っています:
private int conta(int padre)
{
string SQL = "SELECT * FROM categories WHERE idp=@idpadre";
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 idp=@idpadre";
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();
}
}
}
}
while ループの buildParent で "conta" を呼び出しますが、両方のメソッドで同じ SqlConnection (con) を使用すると、リーダーが閉じているときに読み取ろうとするとエラーが発生します。Web サーバーの接続プール、特に最大接続範囲が心配です。それで、どこが間違っているのですか?SqlConnection を管理するためのベスト プラクティスは何ですか? ありがとうございました。