如何将变量传递给SqlCommand语句并插入到数据库表中

Rup*_*ert 2 c# sql sqlcommand executenonquery

我正在用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;
    }
Run Code Online (Sandbox Code Playgroud)

在这段代码中我使用了所有静态值,除了我试图传递给数据库的num变量.

在运行时我收到此错误:

A parameter is missing. [ Parameter ordinal = 1 ]
Run Code Online (Sandbox Code Playgroud)

谢谢

Guf*_*ffa 8

在执行命令之前向命令添加参数:

cmd.Parameters.Add("@num", SqlDbType.Int).Value = num;
Run Code Online (Sandbox Code Playgroud)