关闭函数中的.netslclient数据提供程序
本文关键字:数据 程序 netslclient 函数 | 更新日期: 2023-09-27 18:28:46
我有一个Listview,它绑定到一个名为GetAmountStyles()的函数。当这个函数被触发时,它会创建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();";
}
您正在返回
return "background-color: #FFC6C6;";
在关闭连接之前。作为使用的经验法则,不需要显式处理或关闭。像这样:
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
}
}