SQL Exception: "There is already an open DataReader associated with this Connection which must be closed first"
This exception occurs when a DataReader is still open while attempting to execute another SQL command on the same connection. Here's how to resolve the issue based on the given code:
In your code, you open a DataReader using the ExecuteReader() method and then attempt to execute another command using ExecuteNonQuery(). This is not allowed because the DataReader holds a lock on the connection. To resolve this issue, close the DataReader before executing any additional commands.
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); // Close the DataReader before executing the new command myReader.Close(); cmdInserttblProductFrance.ExecuteNonQuery(); // Now this will execute successfully } } }
After closing the DataReader, you can execute the cmdInserttblProductFrance command without encountering the "There is already an open DataReader associated with this Connection which must be closed first" exception.
The above is the detailed content of How to Resolve the \'There is already an open DataReader...\' SQL Exception?. For more information, please follow other related articles on the PHP Chinese website!