0

I'm working on C# and MySql request. I'm trying to retrieve my datas in my db but I have this error message : Invalid attempt to Read when reader is closed.

Thanks for your help guys :)

I have this function :

public MySqlDataReader GetValueFromTable(string table, ArrayList attribut, ArrayList parameter)
{
   string query = string.Empty;
   MySqlDataReader rdr = null;      
   try
   {
      query = "SELECT * FROM `" + table + "` WHERE ";
      for (int i = 0; i < attribut.Count; i++)
      {
         query += attribut[i] as string;
         query += " = ";
         query += parameter[i] as string;

         if(i != attribut.Count - 1) 
            query += " AND ";
      }

      query += ";";

      using (mysqlConnection)
      {
          using (mysqlCommand = new MySqlCommand(query, mysqlConnection))
          {                  
             rdr = mysqlCommand.ExecuteReader();
          }   
      }
   }
   catch (Exception ex)
   {
      Debug.Log(ex.ToString());
   }
   finally {}

   return rdr;
}

And next somewhere in my code I doing this:

ArrayList attribut = new ArrayList();       
ArrayList parameter = new ArrayList();

attribut.Add("usern_id"); 
parameter.Add("1");     
MySqlDataReader reader = dataBase.GetValueFromTable("papillon", attribut, parameter);
reader.Read();
Debug.Log(reader[0]);
reader.Close();
Tejs
  • 40,736
  • 10
  • 68
  • 86
Pierre
  • 10,593
  • 5
  • 50
  • 80
  • 2
    How is rdr being used? When the using block around the connection exits, the connection closes and the reader closes with it. – JohnC Apr 01 '11 at 17:47
  • Same error in a different scenario http://stackoverflow.com/questions/6775136/invalid-attempt-to-call-read-when-reader-is-closed-error-for-lengthy-operatio – LCJ Nov 20 '12 at 04:39

3 Answers3

7

The using block closes the connection here (on exit)

using (mysqlCommand = new MySqlCommand(query, mysqlConnection))
sehe
  • 374,641
  • 47
  • 450
  • 633
2

If I'm not mistaken, it's the using statement that is killing the reader. Once the using block is terminated, IDisposable will fire on your MySQLConnection, closing and disposing your connection to the database.

BrandonZeider
  • 8,014
  • 2
  • 23
  • 20
1

Your reader is getting closed because it's wrapped in that using statement. When the command and connection are disposed, so is the reader. You'll need to get the data out before disposing the reader.

rsbarro
  • 27,021
  • 9
  • 71
  • 75