C# ExecuteNonQuery "Connection must be valid and open."

Bordotti picture Bordotti · Jun 25, 2014 · Viewed 17.5k times · Source

I'm trying to add values into database, but every time I try to add some thing i get an error in the ExecuteNonQuery() with the message "Connection must be valid and open." And I don't know what to do!!!

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using MySql.Data.MySqlClient;

namespace ClientesClinica
{
    public partial class frmCadastro : Form
    {

    MySqlConnection conect = new MySqlConnection("server = localhost; user id = root; database = clientes; password = '';");

    public frmCadastro()
    {
        InitializeComponent();
    }

    private void frmCadastro_Load(object sender, EventArgs e)
    {

    }

    private void btnCancela_Click(object sender, EventArgs e)
    {
        Close();
    }

    private void btnSalvar_Click(object sender, EventArgs e)
    {

        int cod;
        string nome;
        string end;
        int tel;
        cod = Convert.ToInt16(txtCodigo.Text);

        nome = txtNome.Text;
        end = txtEndereco.Text;


        if (txtNome.Text == "")
        {
            MessageBox.Show("Favor digitar o nome");
        }
        if (txtCodigo.Text == "")
        {
            MessageBox.Show("Favor digitar o código");
        }




        conect.Close();
        MySqlCommand insere = new MySqlCommand();

        insere.CommandText = "INSERT INTO cliente(cod, nome, endereco) Values(@cod + ,'@nome', '@end');";
        insere.Parameters.AddWithValue("@cod", cod);
        insere.Parameters.AddWithValue("@nome", nome);
        insere.Parameters.AddWithValue("@end", end);

            conect.Open();
            insere.ExecuteNonQuery();// THE ERROR IS HERE!!!!
            conect.Close();
            MessageBox.Show("Salvo");




    }

Answer

Jeremy Thompson picture Jeremy Thompson · Jun 25, 2014

You need to open your connection and supply it to the command as per MSDN: SQLCommand

string queryString = "SELECT OrderID, CustomerID FROM dbo.Orders;";
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(queryString, connection);  //<- See here the connection is passes to the command
connection.Open();
SqlDataReader reader = command.ExecuteReader();
try
{
    while (reader.Read())
    {
        Console.WriteLine(String.Format("{0}, {1}",
            reader[0], reader[1]));
    }
}
finally
{
    // Always call Close when done reading.
    reader.Close();
}
}

Or for your usage:

conect.Open(); //<- Open Connection first

MySqlCommand insere = new MySqlCommand();

insere.Connection = conect;  //<- Set the Commands connection

insere.CommandText = "INSERT INTO cliente(cod, nome, endereco) Values(@cod + ,'@nome', '@end');";
insere.Parameters.AddWithValue("@cod", cod);
insere.Parameters.AddWithValue("@nome", nome);
insere.Parameters.AddWithValue("@end", end);
insere.ExecuteNonQuery();
conect.Close();