我有以下代码,但遇到异常:
There is already an open
DataReader
associated with thisConnection
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."
}
}
}
最佳答案
您正在为 DataReader
和 ExecuteNonQuery
使用相同的连接。这不受支持,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/