我收到以下错误:
System.Data.dll中出现未处理的“System.InvalidOperationException”类型异常
其他信息:超时已过期。从池中获取连接之前经过的超时时间。这可能是因为所有池连接都在使用中并且达到了最大池大小。
这是我尝试使用计时器每秒从数据库读取一个值。
以下是代码。我知道这是因为SQL连接没有关闭。但是我可以做些什么来解决它?
public void showcount2(int ID)
{
notifyIcon1.Visible = true;
string count;
string connString = ConfigurationManager.ConnectionStrings["Dbconn"].ToString();
SqlConnection connection = new SqlConnection(connString); // defining sql connection
connection.Open(); // opening connection
SqlCommand cmd1 = connection.CreateCommand();
cmd1.CommandText = "select count from dbo.tblcount where UserID = " + ID;
DataSet datasetFBK1 = new DataSet();
SqlDataAdapter dataadapterFBK1 = new SqlDataAdapter(cmd1);
dataadapterFBK1.Fill(datasetFBK1);
SqlDataReader dr1 = cmd1.ExecuteReader();
if (dr1.Read())
{
string countcheck;
countcheck = notifyIcon2.Text;
count = dr1[0].ToString();
notifyIcon2.Text = "NCT COUNT FOR COLLEAGUE IS: " + count;
if (countcheck == notifyIcon2.Text)
{
return;
}
else
{
notifyIcon2.BalloonTipText = "NCT COUNT FOR COLLEAGUE IS: " + count;
notifyIcon2.ShowBalloonTip(50000);
}
//pick a colored icon based on the count of the NCT cases
if (Convert.ToInt32(count) <= 3)
{
notifyIcon2.Icon = new Icon("C:\\BackupFromPC\\greenicon.ico");
}
else if (Convert.ToInt32(count) > 3 && Convert.ToInt32(count) <= 5)
{
notifyIcon2.Icon = new Icon("C:\\BackupFromPC\\yellowicon.ico");
}
else if (Convert.ToInt32(count) > 5)
{
notifyIcon2.Icon = new Icon("C:\\BackupFromPC\\redicon.ico");
}
//------------------------------
connection.Close();
}
}
答案 0 :(得分:1)
我知道,因为SQL连接没有关闭。但是我可以做些什么来解决它?
好吧,关闭它。最简单的方法是将连接的使用括在using
块中:
using(SqlConnection connection = new SqlConnection(connString))
{
// the rest of your code goes here
}
using
语句转换为try/finally
块。在finally
块中(当return
或以其他方式离开范围时将始终执行)connection
将自动关闭。
答案 1 :(得分:1)
你应该使用:-) 您退出示波器时将处理您使用的所有内容。 包括关闭SqlConnections
像这样:
using (SqlConnection connection = new SqlConnection(connString))
{
using (SqlDataReader dr1 = cmd1.ExecuteReader())
{
if (dr1.Read())
{
string countcheck;
countcheck = notifyIcon2.Text;
count = dr1[0].ToString();
notifyIcon2.Text = "NCT COUNT FOR COLLEAGUE IS: " + count;
if (countcheck == notifyIcon2.Text)
{
return;
}
else
{
notifyIcon2.BalloonTipText = "NCT COUNT FOR COLLEAGUE IS: " + count;
notifyIcon2.ShowBalloonTip(50000);
}
//pick a colored icon based on the count of the NCT cases
if (Convert.ToInt32(count) <= 3)
{
notifyIcon2.Icon = new Icon("C:\\BackupFromPC\\greenicon.ico");
}
else if (Convert.ToInt32(count) > 3 && Convert.ToInt32(count) <= 5)
{
notifyIcon2.Icon = new Icon("C:\\BackupFromPC\\yellowicon.ico");
}
else if (Convert.ToInt32(count) > 5)
{
notifyIcon2.Icon = new Icon("C:\\BackupFromPC\\redicon.ico");
}
//------------------------------
}
}
}