如何给出ADO.NET参数
我想创建一个向DB添加记录的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);
在您的情况下,看起来您正在使用.NET。 使用参数非常简单:
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);
应该使用以下内容:
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();
假设@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所示。
我觉得这对你很有用
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();
试试这个
command.Parameters.AddWithValue("@parameter",yourValue); command.ExecuteNonQuery();
我的意思是你忘了使用command.executeNonQuery();