error when trying to read data from the database (Connection must be valid and open). C #

0

What I would like to do is to be able to read record by record as the table is advanced, just to be able to extract the record that I want whenever I want, add a Mysql reader for that, but I do not know why motive marks me the following error:

  

Connection must be valid and open.

Connection Code

        server = "localhost";
        database = "presupuesto";
      uid = "root";
        password = "";
        string connectionString;
        connectionString = "SERVER=" + server + ";" + "DATABASE=" +
        database + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";";
       connection = new MySqlConnection(connectionString);


       string Query = "select Id_Compra,Articulo,Categoria,Obligatorio,Costo,Adquirir from compra";
       MySqlConnection MyConn2 = new MySqlConnection(connectionString);
       MySqlCommand MyCommand2 = new MySqlCommand(Query, MyConn2); 
       //For offline connection we weill use  MySqlDataAdapter class.  
       MySqlDataAdapter MyAdapter = new MySqlDataAdapter();
       MyAdapter.SelectCommand = MyCommand2;
       DataTable dTable = new DataTable();

Reading Code.

if (this.connection.State == ConnectionState.Closed)
           {
               this.connection.Open();
               MySqlDataReader rdr = MyCommand2.ExecuteReader();
               while (rdr.Read())
               {
                   for (int x = 0; x < 10; x++)
                   {
                       MessageBox.Show(Convert.ToString(x), "Inidce", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                   }

               }
           }
    
asked by David 18.01.2017 в 16:29
source

2 answers

2
    MyConn2.Open();
    MySqlDataReader rdr = MyCommand2.ExecuteReader();
    while (rdr.Read())
    {
         //Codigo que deseas usar en el reader
    }
    MyConn2.Close();

In your code the DataReader rdr has assigned the MyConn2 connection and it depends on it being open to make the query on the database, in the code block that you provide, I can not find anything that indicates that:

    this.connection

Be a valid and instantiated connection

Greetings

    
answered by 18.01.2017 / 20:12
source
0

To avoid these connection problems, you can do them in the following way ...

       using(MySqlConnection MyConn2 = new MySqlConnection(connectionString)){
                 MyConn2.Open();
                 MySqlDataReader rdr = MyCommand2.ExecuteReader();
                 while (rdr.Read())
                 {
                      for (int x = 0; x < 10; x++)
                      {
                             MessageBox.Show(Convert.ToString(x), "Inidce", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                      }

                 }
                 rdr.Close();
       }

With this you avoid problems of having open connections and not being able to open other

    
answered by 18.01.2017 в 20:17