C# – There is already an open DataReader associated with this Connection which must be closed first

cdatabaseMySQLnetvisual studio

I am using Visual Studio 2010 (C#) with mysqlConnector and everything seems to be fine.
However, when I try to request something from the server I get this error:

"There is already an open DataReader associated with this Connection which must be closed first."

This is my code:

gc.connect();

List<Conseiller> conseillers = gc.getAllConseillers();

--

public void connect() 
{
    string connStr = "SERVER=localhost;UID=root;DATABASE=Projet;Password=root";
    oConn = new MySqlConnection(connStr);

    try 
    {
        oConn.Open();
        Console.WriteLine("Successfully connected to the data base");
    } 
    catch (OdbcException caugth) 
    {
        /* Traitement de l'erreur */
        Console.WriteLine(caugth.Message);
    }
}

-- 

public List<Conseiller> getAllConseillers()
{
    MySqlCommand oComm = oConn.CreateCommand();

    oComm = oConn.CreateCommand();

    Console.WriteLine("SELECT * FROM conseillers");
    oComm.CommandText = "SELECT * FROM conseillers";

    MySqlDataReader oReader = oComm.ExecuteReader(); // Error here
}

Where I am wrong ?

Best Answer

don't try to separate the connect with the get data. The call to Open may in-fact not go to the database at all and you will not detect issues at that point. Note the using statement to close the connection. add SEH as required

List<Conseiller> conseillers = gc.getAllConseillers();

public void getAll() {
  string connStr = "SERVER=localhost;UID=root;DATABASE=Projet;Password=root";
  using (oConn = new MySqlConnection(connStr))
  using (MySqlCommand oComm = oConn.CreateCommand())
  {
    oConn.Open();
    oComm.CommandText = "SELECT * FROM conseillers";

    MySqlDataReader oReader = oComm.ExecuteReader(); // no Error here
    // user reader here
    } catch (OdbcException caugth) {
        /* Traitement de l'erreur */
        Console.WriteLine(caugth.Message);
    }
 }