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

Rupert picture Rupert · Oct 30, 2010 · Viewed 28.7k times · Source

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

Answer

Guffa picture Guffa · Oct 30, 2010

Add a parameter to the command before executing it:

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