已经有一个打开的DataReader与此命令关联,必须先在C#中关闭它
本文关键字:关联 有一个 DataReader 命令 | 更新日期: 2023-09-27 18:19:33
我有下面的代码,我得到了异常
"已经有一个打开的DataReader与此连接关联必须先关闭"。
我正在使用Microsoft Visual C#2010学习版和Microsoft Access 2007进行此项目。
namespace Database1
{
public partial class Form1 : Form
{
OleDbConnection connection;
public void connect()
{
connection = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;DataSource=|DataDirectory|'PBName1.accdb;Data Source=C:'Users'bvino_000'Downloads'PBName1.accdb");
connection.Open();
}
public void close_connection()
{
connection.Close();
}
public Form1()
{
InitializeComponent();
connect();
OleDbDataReader reader = null;
OleDbCommand command = new OleDbCommand("SELECT * from PBInfo", connection);
reader = command.ExecuteReader();
while (reader.Read())
{
listBox1.Items.Add(reader[1].ToString());
}
close_connection();
}
private void button1_Click(object sender, EventArgs e)
{
listBox2.Items.Add(listBox1.SelectedItem);
string s = "";
s = listBox1.SelectedItem.ToString();
connect();
string sql = "SELECT PBSize FROM PBInfo where PBName=" + " '" + s + "' ";
try
{
OleDbDataReader reader = null;
OleDbCommand command = new OleDbCommand(sql, connection);
reader = command.ExecuteReader(CommandBehavior.CloseConnection);
while (reader.Read())
{
command.ExecuteReader();
}
reader.Close();
command.Dispose();
close_connection();
if (connection.State != ConnectionState.Open)
{
connection.Open();
}
label2.Text = command.ExecuteReader().ToString();
listBox1.Items.Remove(listBox1.SelectedItem);
}
catch(Exception ex)
{
ex.GetBaseException();
}
finally
{
close_connection();
}
}
}}
Form构造函数中的读取器未关闭。您应该考虑使用using构造来避免这种情况:
using (var reader = command.ExecuteReader(CommandBehavior.CloseConnection))
{
...
}
您忘记关闭表单构造器上的读取器。当您执行按钮1_点击一个读卡器已准备好打开
public Form1()
{
InitializeComponent();
connect();
OleDbDataReader reader = null;
OleDbCommand command = new OleDbCommand("SELECT * from PBInfo", connection);
reader = command.ExecuteReader();
while (reader.Read())
{
listBox1.Items.Add(reader[1].ToString());
}
**reader.Close();
command.Dispose();**
//close_connection();
}
来自Retrieving Data Using a DataReader
请注意,当DataReader打开时,Connection正在使用由该DataReader独家提供。不能执行的任何命令连接,包括创建另一个DataReader,直到原始DataReader已关闭
您应该关闭当前的OleDbDataReader
,或者为每个OleDbDataReader
定义不同的OleDbConnection
。