Reputation:
I want to create a SQL command that adds record to DB. I tried the following code but it doesn't seem to be working:
SqlCommand comand = new SqlCommand("INSERT INTO Product_table Values(@Product_Name,@Product_Price,@Product_Profit,@p)", connect);
SqlParameter ppar = new SqlParameter();
ppar.ParameterName = "@Product_Name";
ppar.Value = textBox1.Text;
MessageBox.Show("Done");
comaand.Parameters.Add(ppar);
Upvotes: 2
Views: 18537
Reputation: 2930
Should use something like the following:
SqlCommand cmd = new SqlCommand("INSERT INTO Product_table Values(@Product_Name, @Product_Price, @Product_Profit, @p)", connect);
cmd.Parameters.Add("@Product_Name", SqlDbType.NVarChar, ProductNameSizeHere).Value = txtProductName.Text;
cmd.Parameters.Add("@Product_Price", SqlDbType.Int).Value = txtProductPrice.Text;
cmd.Parameters.Add("@Product_Profit", SqlDbType.Int).Value = txtProductProfit.Text;
cmd.Parameters.Add("@p", SqlDbType.NVarChar, PSizeHere).Value = txtP.Text;
cmd.ExecuteNonQuery();
Assuming @p parameter is some NVarChar.
Better avoid using AddWithValue, see why here: https://blogs.msmvps.com/jcoehoorn/blog/2014/05/12/can-we-stop-using-addwithvalue-already/
Also at INSERT SQL statement better provide names of the values (as defined in the database) before the values themselves, as shown at https://www.w3schools.com/sql/sql_insert.asp
Upvotes: 9
Reputation: 84
I think this is useful for u
SqlCommand command = new SqlCommand("inserting", con);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add("@Firstname", SqlDbType.NVarChar).Value = TextBox1.Text;
command.Parameters.Add("@Lastname", SqlDbType.NVarChar).Value = TextBox2.Text;
command.ExecuteNonQuery();
Upvotes: 1
Reputation: 272
Try this
command.Parameters.AddWithValue("@parameter",yourValue);
command.ExecuteNonQuery();
I mean you forgot to use command.executeNonQuery();
Upvotes: -1
Reputation: 985
In your case, it looks like you're using .NET. Using parameters is as easy as:
C#
string sql = "SELECT empSalary from employee where salary = @salary";
SqlConnection connection = new SqlConnection(/* connection info */);
SqlCommand command = new SqlCommand(sql, connection);
command.Parameters.AddWithValue("salary", txtSalary.Text);
Upvotes: 4