0

我有一个绑定到名为 GetAmountStyles() 的函数的 Listview。当这个函数被触发时,它会创建 44 个 sql 连接。无论我在哪里尝试关闭 SQL 连接,它都不会关闭。我在哪里以及如何关闭这些连接?

 protected string GetAmountStyle()
{
    //Makes SQl connection 
    SqlConnection testDBconn = new SqlConnection(ConfigurationManager.ConnectionStrings["testDBconn"].ConnectionString);
    //SqlCommand cmd = new SqlCommand();
   testDBconn.Open();

    System.Data.SqlClient.SqlCommand CurrAllsessions = new System.Data.SqlClient.SqlCommand("Select UserName from TenHrsLogins union Select UserName from permlogins ", testDBconn);
    SqlDataReader dr = CurrAllsessions.ExecuteReader();
    string Login = Convert.ToString(Eval("Login"));




    while (dr.Read())
    {
        //if (Login.Contains(dr.GetValue(0).ToString()) == true)
        if (Login.Contains(dr.GetValue(0).ToString()) == true)
        {

            dr.Dispose();
            return "background-color: #FFC6C6;";



        }
        else
        {



        }


    }
    dr.Dispose();
    testDBconn.Close();
    return "testDBconn.Close();";
}
4

1 回答 1

1

你回来了

return "background-color: #FFC6C6;";

在关闭连接之前。作为使用 using 的经验法则,无需显式处置或关闭。像这样:

using(var testDBconn = new SqlConnection(...)) {
   testDBconn.Open();
   // do whatever you like with connection, it will close automatically
   using(var dr = CurrAllsessions.ExecuteReader()) {
     // do whatever you like with data reader
   }
}
于 2013-08-23T20:47:58.343 回答