如何将变量传递给SqlCommand语句并插入到数据库表中
我正在用C#编写一个小程序,它使用SQL在运行时根据用户的输入将值存储到数据库中。
唯一的问题是我无法找出正确的Sql语法来将变量传递到我的数据库中。
private void button1_Click(object sender, EventArgs e) { int num = 2; using (SqlCeConnection c = new SqlCeConnection( Properties.Settings.Default.rentalDataConnectionString)) { c.Open(); string insertString = @"insert into Buildings(name, street, city, state, zip, numUnits) values('name', 'street', 'city', 'state', @num, 332323)"; SqlCeCommand cmd = new SqlCeCommand(insertString, c); cmd.ExecuteNonQuery(); c.Close(); } this.DialogResult = DialogResult.OK; }
在这段代码中,我使用了所有静态值,除了我试图传递给数据库的num变量。
在运行时我收到此错误:
A parameter is missing. [ Parameter ordinal = 1 ]
谢谢
在执行命令之前向命令添加参数:
cmd.Parameters.Add("@num", SqlDbType.Int).Value = num;
您没有在SQL语句中为@
参数提供值。 @
符号表示一种占位符,您将在其中传递值。
使用SqlParameter对象,如本例所示 ,将值传递给该占位符/参数。
有许多方法可以构建参数对象(不同的重载)。 一种方法,如果您遵循相同类型的示例,则在声明命令对象的位置之后粘贴以下代码:
// Define a parameter object and its attributes. var numParam = new SqlParameter(); numParam.ParameterName = " @num"; numParam.SqlDbType = SqlDbType.Int; numParam.Value = num; // <<< THIS IS WHERE YOUR NUMERIC VALUE GOES. // Provide the parameter object to your command to use: cmd.Parameters.Add( numParam );