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
Add a parameter to the command before executing it:
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: