循环内的C#SqlConnection

1 c# loops sqlconnection

第一次在stackoverflow上。我正在学习如何在WebForm页面中管理SqlConnection,并且我想要达到最佳实践。在我的特定情况下,我有一个循环,如果我没有为循环的每个迭代设置新的SqlConnection(错误是关于在关闭阅读器时尝试读取的信息),则我将无法运行代码而不会出错。 。因此,我在PageLoad方法中声明了这一点:

private SqlConnection con;
protected void Page_Load(object sender, EventArgs e)
{
    con = new SqlConnection(connectionString);
}
Run Code Online (Sandbox Code Playgroud)

然后我有这个:

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("&nbsp;&nbsp;&nbsp;&nbsp;"));
    }
    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();
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

在while循环的buildParent中,我称为“ conta”,但是如果我对这两种方法使用相同的SqlConnection(con),则在关闭阅读器时会出现尝试读取错误。我担心Web服务器上的连接池,尤其是最大连接范围。那么,我哪里错了?什么是管理SqlConnection的最佳实践?谢谢。

Fil*_*Vos 5

您尽可能晚地打开连接,并尽快进行处置。让连接池处理回收连接。

我通常这样编写代码:

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.
Run Code Online (Sandbox Code Playgroud)

注意:要从SQL数据库中获取计数,最好使用

SELECT count(*) FROM categories WHERE idp=@idpadre
Run Code Online (Sandbox Code Playgroud)

并执行查询 ExecuteScalar()