c# - 异常 : There is already an open DataReader associated with this Connection which must be closed first

标签 c# mysql

我有以下代码,但遇到异常:

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

我在这个项目中使用 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."
        }
    }
}

最佳答案

您正在为 DataReaderExecuteNonQuery 使用相同的连接。这不受支持,according to MSDN :

Note that while a DataReader is open, the Connection is in use exclusively by that DataReader. You cannot execute any commands for the Connection, including creating another DataReader, until the original DataReader is closed.

2018 年更新:链接到 MSDN

关于c# - 异常 : There is already an open DataReader associated with this Connection which must be closed first,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5440168/

相关文章:

c# - 仁慈SSH.NET : Is it possible to create a folder containing a subfolder that does not exist

c# - .NET 核心与 MySQL

MySQL查询通过查看历史日志来找出当前状态

python - 保存到数据库以防止Python中的SQL注入(inject)

c# - EF Core 3.1 查询有时超快但有时很慢

c# - 为混合代码 DLL 中_caught_ SEH 异常生成小型转储

c# - 使用 FakeItEasy 创建类并自动初始化依赖项

c# - 常量字段或获取属性

mysql - 按计数对查询结果进行分组

mySQL - 显示每天的第一个和最后一个日志