C# 关於数据库连接关闭的异常

来源:百度知道 编辑:UC知道 时间:2024/07/05 02:56:02
private void button8_Click(object sender, EventArgs e)//点击 帐户查询
{
this.sqlConnection1.Open();
SqlCommand sqlcon6 = new SqlCommand();
sqlcon6.Connection = this.sqlConnection1;
sqlcon6.CommandText = "select Caccount from enter_Customer";
SqlDataReader dr1=sqlcon6.ExecuteReader();
while (dr1.Read())
{
this.CustomerMessagelistBox.Items.Add(dr1[0].ToString());
}
this.sqlConnection1.Close();
}

系统提示异常:没有关闭连接,但是最后一句我不是已经关闭了吗?本人菜鸟,请高手给出详细指点,谢谢
都不是啊~~~ 还是提示“连接未关闭”

你仅仅是关闭了数据库链接,并没有关闭SqlDataReader的链接
应该在this.sqlConnection1().close()之前加上
dr1.Close();
dr1.Dispose();

dr1.close();
this.sqlConnection1.Close();

dr1.close();
this.sqlConnection1.Close();
建议你使用下面的方式来打开连接
using(this.sqlConnection1){
//处理代码
SqlCommand sqlcon6 = new SqlCommand();
sqlcon6.Connection = this.sqlConnection1;
sqlcon6.CommandText = "select Caccount from enter_Customer";
SqlDataReader dr1=sqlcon6.ExecuteReader();
while (dr1.Read())
{
this.CustomerMessagelistBox.Items.Add(dr1[0].ToString());
}
使用using会自动帮你关闭连接
}