如何将变量传递到SqlCommand语句并插入到数据库表中
问题描述:
我正在编写一个C#中的小程序,它使用SQL将运行时的值存储到数据库中,并基于用户的输入。如何将变量传递到SqlCommand语句并插入到数据库表中
唯一的问题是我无法弄清楚正确的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这样的对象可以在this example中看到将值传递给该占位符/参数。
构建参数对象有许多方法(不同的重载)。一种方式,如果你遵循同样的例子,就是在声明命令对象的位置后面粘贴下面的代码:
// 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);
这正是我所需要的。感谢您及时的回复。 – Rupert 2010-10-30 01:47:49