我想创建一个将记录添加到数据库的SQL命令。我尝试了以下代码,但似乎无法正常工作:
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);
Run Code Online (Sandbox Code Playgroud)
应该使用如下内容:
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();
Run Code Online (Sandbox Code Playgroud)
假设@p参数是一些NVarChar。
最好避免使用AddWithValue,请在此处查看原因:https://blogs.msmvps.com/jcoehoorn/blog/2014/05/12/can-we-stop-using-addwithvalue-already/
同样在INSERT SQL语句中,最好在值本身之前提供值的名称(在数据库中定义),如https://www.w3schools.com/sql/sql_insert.asp所示