简体   繁体   中英

An unhandled exception of type 'System.InvalidOperationException' occurred in System.Data.dll - C# visual studio

i've got this code lines, when i try to save my data to data base shows that error:

An unhandled exception of type 'System.InvalidOperationException' occurred in System.Data.dll

Additional information: ExecuteNonQuery: A propriedade Connection não foi inicializada.

can you guys give a little help ?

SqlConnection cn = new SqlConnection(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\basededadospap.mdf;Integrated Security=True;Connect Timeout=30");
        SqlCommand cmd = new SqlCommand();

private void button1_Click(object sender, EventArgs e)
        {

            if (textBox4.Text != "" & textBox2.Text != "")
            {
                {
                    using (var connection = new SqlConnection(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\basededadospap.mdf;Integrated Security=True;Connect Timeout=30"))
                    {
                        cn.Open();
                        cmd.CommandText = "INSERT INTO artigo (nomeartigo,preco) VALUES ('" + textBox4.Text + "','" + textBox2.Text + "')";
                        cmd.ExecuteNonQuery();
                        cmd.Clone();
                        MessageBox.Show(" Artigo inserido com sucesso! ");
                        this.Close();
                    }
                }
            }
        }

Its because you didn't tell your command to use the connection try this:

SqlCommand cmd = new SqlCommand(
    "Query String",
    cn);

You have to tell your command which connection to use to query data. I see your connection is named cn, so that is what we have to pass to the SQLCommand constructor.

So your full code would look something like:

using (SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\basededadospap.mdf;Integrated Security=True;Connect Timeout=30"))
{
    con.Open();
    SqlCommand cmd = new SqlCommand("SELECT TOP 3 * FROM Dogs1 ORDER BY Weight", con);
    cmd.ExecuteNonQuery();
    cmd.Clone();
    MessageBox.Show(" Artigo inserido com sucesso! ");
    this.Close();
}

Do you notice how I passed the SQL command my connection variable?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM