c# - 已经有一个打开的 DataReader 与此命令关联,必须先关闭
问题描述
namespace ttt
{
public partial class student : Form
{
SqlConnection conn = new SqlConnection(@"Data Source=DESKTOP-R0N4ID3;Initial Catalog=testOnedb;Integrated Security=True");
SqlCommand com;
SqlDataReader read;
public student()
{
InitializeComponent();
com = new SqlCommand("select * from testOnetable",conn);
conn.Open();
com.ExecuteReader();
SqlDataReader read = com.ExecuteReader();
while (read.Read())
{
listBox1.Items.Add("the username : " + read["username"].ToString() + "\n the passward : " + read["passward"].ToString() + "\n the email : " + read["email"].ToString());
}
read.Close();
conn.Close();
}
}
}
解决方案
您需要将数据库交互元素的初始化(例如SqlConnection
and SqlDataReader
)包装在using
块中,以便Dispose
在完成它们(或手动执行)时调用方法:
using (SqlCommand com = new SqlCommand("select * from testOnetable", conn))
using (SqlDataReader read = com.ExecuteReader()) {
....
}
关闭SqlDataReader
并不会消除它对事物的持有(我不确定特别是它的技术细节)。
此外,每次构建新student
实例时都打开一个新连接对数据库不利。您应该使用单例模式并拥有专用的数据访问对象类。