Reputation: 9
private void btn_add_store_Click(object sender, EventArgs e)
{
cmd = new SqlCommand("Insert into Product values("+sa_code+",'" +pro_name+ "',"+quantity+",'"+price+"','"+notes+"')", con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
Upvotes: 0
Views: 113
Reputation: 9
cmd = new SqlCommand("Insert into Product(Code, Name, Quantity, Price, Notes)values('"+sa_code.Text+ "','"+pro_name.Text+"','"+ quantity.Text + "','"+price.Text+"','"+notes.Text+"')", con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
//this is the right answer
Upvotes: 0
Reputation: 1062800
Without seeing what the final composed value of the CommandText
was, it is hard to comment specifically - as it will depend on the values being passed in, but ultimately the problem here is that it depends on the values being passed in. You should never concatenate values to create SQL, basically - it leaves you vulnerably to malicious SQL injection, or accidental bugs due to things like quotes in fields. There's also a secondary problem of the ambiguous column order. I cannot advocate strongly enough that you should use parameters here (and also name the columns); for example:
insert into Product (Code, ProductName, Quantity, Price, Notes)
values (@sa_code, @pro_name, @quantity, @price, @notes);
But then we need to pass those parameters in; a tool like Dapper would make this painless:
using Dapper; // at the top of the file
...
con.Execute(@"
insert into Product (Code, ProductName, Quantity, Price, Notes)
values (@sa_code, @pro_name, @quantity, @price, @notes);",
new { sa_code, pro_name, quantity, price, notes });
Here, Dapper will deal with adding all the parameters for you; it will also handle opening and closing the connection on your behalf.
Upvotes: 4