Skip to main content
 首页 » 编程设计

c#之已经有一个打开的 DataReader 与此命令关联,必须先在 C# 中将其关闭

2024年02月13日11kevingrace

我有以下代码,但出现异常

"There is already an open DataReader associated with this Connection which must be closed first".

我正在为此项目使用 Microsoft Visual C# 2010 Express 和 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)) 
{ 
   ...  
}