How to pass variable into SqlCommand statement and

2020-02-07 05:11发布

I'm writing a small program in C# that uses SQL to store values into a database at runtime based on input by the user.

The only problem is I can't figure out the correct Sql syntax to pass variables into my database.

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;
    }

In this code snippet I'm using all static values except for the num variable which I'm trying to pass to the database.

At runtime I get this error:

A parameter is missing. [ Parameter ordinal = 1 ]

Thanks

2条回答
老娘就宠你
2楼-- · 2020-02-07 05:41

Add a parameter to the command before executing it:

cmd.Parameters.Add("@num", SqlDbType.Int).Value = num;
查看更多
手持菜刀,她持情操
3楼-- · 2020-02-07 05:41

You didn't provide a value for the @ parameter in the SQL statement. The @ symbol indicates a kind of placeholder where you will pass a value through.

Use an SqlParameter object like is seen in this example to pass a value to that placeholder/parameter.

There are many ways to build a parameter object (different overloads). One way, if you follow the same kind of example, is to paste the following code after where your command object is declared:

        // 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 );
查看更多
登录 后发表回答