MySql.Data.MySqlClient.MySqlException: 'Invalid attempt to Read when reader is closed.'

I am coding in ASP.NET (c# for code behind). The following code gives me a bug and I am not sure how to solve the problem

foreach (var sids in siddict) {     int sid = sids.Key;     string gra = sids.Value;     if (gra != string.Empty)     {         MySqlCommand cmd3 = new MySqlCommand("select classid,day,TIME_FORMAT(start,'%H:%i'),TIME_FORMAT(end,'%H:%i'),teacher from enroll where [email protected]", sqlconn);         cmd3.Parameters.AddWithValue("@sid", sid);         MySqlCommand cmd3 = new MySqlCommand("select classid,day,TIME_FORMAT(start,'%H:%i'),TIME_FORMAT(end,'%H:%i'),teacher from enroll where [email protected]", sqlconn);         cmd3.Parameters.AddWithValue("@sid", sid);         MySqlDataReader sdr2 = cmd3.ExecuteReader();         while (sdr2.Read())         {             string clid = sdr2.GetString(0);             string couid = sdr2.GetString(0).Split('-')[0] + "-" +b sdr2.GetString(0).Split('-')[1];             string day = sdr2.GetString(1).ToLower();             string start = sdr2.GetString(2) + ":00";             string end = sdr2.GetString(3) + ":00";             string teacher = sdr2.GetString(4);             sqlconn.Close();             sqlconn.Open();             MySqlCommand cmd4 = new MySqlCommand("select " + gra + " from classes where [email protected] and " + gra + " is null", sqlconn);             cmd4.Parameters.AddWithValue("@cid", couid);             MySqlDataReader sdr3 = cmd4.ExecuteReader();             if (sdr3.Read())             {                 sqlconn.Close();                 sqlconn.Open();                 MySqlCommand cmd5 = new MySqlCommand("delete from enroll where classid = @clid and [email protected];update " + day + " set currentstudent=currentstudent-1 where [email protected] and [email protected] and [email protected] and [email protected]", sqlconn);                 cmd5.Parameters.AddWithValue("@clid", clid);                 cmd5.Parameters.AddWithValue("@sid", sid);                 cmd5.Parameters.AddWithValue("@start", start);                 cmd5.Parameters.AddWithValue("@end", end);                 cmd5.Parameters.AddWithValue("@teacher", teacher);                 cmd5.ExecuteNonQuery();             }         }     } } 

This gives an error of connection MySql.Data.MySqlClient.MySqlException: 'Invalid attempt to Read when reader is closed.' . I think it is because I closed it’s original connection of reading sdr2 when opening a new connection for sdr3 and for cmd5. Any way to solve this?

Add Comment
0 Answer(s)

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.