Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ExecuteNonQuery not working in C#

I am building a database using Visual Studio 2008 c# and when I'm a trying to insert a new record into my database it appears that ExecuteNonQuery has not initialized. I copy my code, hope anyone can help me in this because I am new.

 private void button1_Click(object sender, EventArgs e)
 {
     SqlConnection cn = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\Usuario\Documents\Visual Studio 2010\Projects\Nova\Nova\Database1.mdf;Integrated Security=True;User Instance=True");
     SqlCommand cmd = new SqlCommand();
     cn.Open();
     cmd.CommandText = "insert into Database1.mdf(Codigo,Nombre,Cantidad,Tipo) values('"+comboBox1.Text+"','"+textBox3.Text+"','"+textBox1.Text+"','"+comboBox2.Text+"')";
     cmd.ExecuteNonQuery();
     cmd.Clone();
     cn.Close();
     MessageBox.Show("Acabas de agregar un producto");
 }
like image 462
Ivan Fernandez Avatar asked May 29 '26 04:05

Ivan Fernandez


2 Answers

You haven't set the connection to your command:

cmd.Connection = cn;
like image 178
Fabian Bigler Avatar answered May 31 '26 17:05

Fabian Bigler


You have numerous problems in your code:

  • First: The insert into statement requires a target datatable not the name of the MDF file
  • Second: Employ the using statement to close and dispose the connections
  • Third: Parametrized query to avoid parsing problems and sql injections
  • Fourth: You need to associate the connection to the command (Easily done at the SqlCommand constructor)

    using(SqlConnection cn = new SqlConnection(.......))
    using(SqlCommand cmd = new SqlCommand("insert into table_name(Codigo,Nombre,Cantidad,Tipo)" + 
                              "values (@cod, @nom,@can,@tipo)", con))
    {
        cn.Open();
        cmd.Parameters.AddWithValue("@cod", comboBox1.Text);
        cmd.Parameters.AddWithValue("@nom", textBox3.Text);
        cmd.Parameters.AddWithValue("@can", textBox1.Text);
        cmd.Parameters.AddWithValue("@tipo", comboBox2.Text);
        cmd.ExecuteNonQuery();
        MessageBox.Show("Acabas de agregar un producto");
    }
    

EDIT The information provided by the link added by @RemusRusanu below is very important. The use of AddWithValue, whilst handy, could hinder the performance of your query. The correct approach should be the usage of a proper defined SqlParameter with both explicit datatype and parameter size. As an example

SqlParameter p = new SqlParameter("@cod", SqlDbType.NVarChar, 255).Value = comboBox1.Text;
cmd.Parameters.Add(p);

But, of course, this requires that you check the exact datatype and size of your columns.

like image 45
Steve Avatar answered May 31 '26 17:05

Steve



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!