例外:已经有一个与此连接关联的打开的 DataReader 必须先关闭 [英] Exception: There is already an open DataReader associated with this Connection which must be closed first

查看:45
本文介绍了例外:已经有一个与此连接关联的打开的 DataReader 必须先关闭的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have below code and I am getting exception:

已经有一个打开的 DataReader 与这个 Connection 相关联,必须先关闭它.

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();

I am using Visual Studio 2010/.Net 4.0 and MySQL for this project. Basically I am trying to run another SQL statement while using data reader to do my other task. I am getting exception at line 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 使用相同的连接.这不受支持,根据 MSDN:

You are using the same connection for the DataReader and the ExecuteNonQuery. This is not supported, according to MSDN:

请注意,当 DataReader 打开时,连接正在使用中仅由该 DataReader 提供.您不能执行任何命令连接,包括创建另一个 DataReader,直到原始 DataReader 已关闭.

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

这篇关于例外:已经有一个与此连接关联的打开的 DataReader 必须先关闭的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆