开发者

How to pass variable into SqlCommand statement and insert into database table

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开发者_StackOverflow中文版, 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


Add a parameter to the command before executing it:

cmd.Parameters.Add("@num", SqlDbType.Int).Value = num;


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 );
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜