例外:已经有一个与此Connection关联的开放DataReader必须先关闭

Lor*_*ing 24 c# mysql

我有以下代码,我得到例外:

已经有一个DataReader与此相关的开放Connection,必须先关闭.

我在这个项目中使用Visual Studio 2010/.Net 4.0和MySQL.基本上我在尝试使用数据读取器执行其他任务时运行另一个SQL语句.我正在排队cmdInserttblProductFrance.ExecuteNonQuery();

SQL = "Select * from tblProduct";

//Create Connection/Command/MySQLDataReader
MySqlConnection myConnection = new MySqlConnection(cf.GetConnectionString());
myConnection.Open();
MySqlCommand myCommand = new MySqlCommand(SQL, myConnection);
MySqlDataReader myReader = myCommand.ExecuteReader();
myCommand.Dispose();

if (myReader.HasRows)
{
    int i = 0;
    // Always call Read before accessing data.
    while (myReader.Read())
    {
        if (myReader["frProductid"].ToString() == "") //there is no productid exist for this item
        {
            strInsertSQL = "Insert Into tblProduct_temp (Productid) Values('this istest') ";
            MySqlCommand cmdInserttblProductFrance = new MySqlCommand(strInsertSQL, myConnection);
            cmdInserttblProductFrance.ExecuteNonQuery(); //<=====THIS LINE THROWS "C# mySQL There is already an open DataReader associated with this Connection which must be closed first."
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Dav*_*rez 40

您正在使用的相同的连接DataReaderExecuteNonQuery.根据MSDN,这不受支持:

请注意,当DataReader打开时,Connection仅由该DataReader使用.在原始DataReader关闭之前,您无法为Connection执行任何命令,包括创建另一个DataReader.

更新2018年:链接到MSDN


Jos*_* M. 25

总是,总是将一次性对象放在using语句中.我看不出你是如何实例化你的DataReader但你应该这样做:

using (Connection c = ...)
{
    using (DataReader dr = ...)
    {
        //Work with dr in here.
    }
}
//Now the connection and reader have been closed and disposed.
Run Code Online (Sandbox Code Playgroud)

现在,为了回答您的问题,读者使用与您尝试的命令相同的连接ExecuteNonQuery.您需要使用单独的连接,因为DataReader会保持连接打开并根据需要读取数据.


Bro*_*ass 10

您正尝试在ExecuteNonQuery()此读取器已使用的SQL连接上插入(with ):

while (myReader.Read())
Run Code Online (Sandbox Code Playgroud)

首先读取列表中的所有值,关闭阅读器然后执行插入,或使用新的SQL连接.


小智 9

只需MultipleActiveResultSets=True在您的连接字符串中使用。

  • System.ArgumentException:不支持选项 - 使用 Visual Studio 2019 (2认同)

小智 8

添加MultipleActiveResultSets=true到文件 appsettings.json 中连接字符串示例的提供程序部分

"ConnectionStrings": {
"EmployeeDBConnection": "server=(localdb)\\MSSQLLocalDB;database=YourDatabasename;Trusted_Connection=true;MultipleActiveResultSets=true"}
Run Code Online (Sandbox Code Playgroud)