Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
406 views
in Technique[技术] by (71.8m points)

c# - How to give ADO.NET Parameters

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);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...