0

I am getting the error

"Connection must be valid and open"

and I don't know what is giving me the error, please help

        string connection = @"datasource=xxx;port=xxx;username=root;password=xxx";
        MySqlConnection conn = new MySqlConnection(connection);
        MySqlCommand add = new MySqlCommand("Insert Into pap.testes (Cod_Teste,Data,Hora,Cod_Modulo,N_Processo,Nome_Teste) Values ("+ this.cod_teste.Text + "," + this.data.Text + "," + this.hora.Text + ","+ this.modulos.Text +" , " +@Entrada.PassingLoginText+ " ," + this.nome_teste.Text + " )");
        MySqlDataReader reader;

        try
        {
            conn.Open();
            reader = add.ExecuteReader();
            MessageBox.Show("Registo Inserido");
            while(reader.Read())
            {

            }

        }


        catch(Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
Soner Gönül
  • 97,193
  • 102
  • 206
  • 364

2 Answers2

1
    string connection = @"datasource=xxx;port=xxx;username=root;password=xxx";
    MySqlConnection conn = new MySqlConnection(connection);
    MySqlCommand add = conn.CreateCommand(); // important
    add.CommandText= "Insert Into pap.testes (Cod_Teste,Data,Hora,Cod_Modulo,N_Processo,Nome_Teste) Values ("+ this.cod_teste.Text + "," + this.data.Text + "," + this.hora.Text + ","+ this.modulos.Text +" , " +@Entrada.PassingLoginText+ " ," + this.nome_teste.Text + " )";
    MySqlDataReader reader;

    try
    {
        conn.Open();
        reader = add.ExecuteReader();
        MessageBox.Show("Registo Inserido");
        while(reader.Read())
        {

        }
    }

    catch(Exception ex)
    {
        MessageBox.Show(ex.Message);
    }

    finaly
    {
         conn.Close();
    }
0

Add this line before executing the command:

add.Connection = conn;

A command requires a Connection and you didn't provide yours with one.

Youssef Lourayad
  • 337
  • 3
  • 14