I am having trouble using parameters in C# to insert into a SQL Database. My connection is already working
I have tried the Add, AddWithValue
static void parameter_insert(SqlConnection conn, int number)
{
try
{
conn.Open();
SqlCommand command = new SqlCommand(@"INSERT INTO test1.dbo.shopping_list(NAME, QUANTITY, QUALITY, FOOD_GROUP, FOODS VALUES('Bread', @Quantity, 'Poor', 'Carbs', 'Good')", conn);
command.Parameters["@Quantity"].Value = 3;
command.ExecuteNonQuery();
Console.WriteLine("Parameter insertion successful.");
}
catch
{
Console.WriteLine("Parameter insertion failed.");
}
}
The output gives me the insertion failed
catchwith its uninformative error message. You should get a syntax error that actually tells you what the problem is. (Or first anIndexOutOfRangeExceptionfor the parameter you did not add to the collection.) Proper exception handling would at the very least involve something likecatch (SqlException e) { Console.WriteLine("Insertion failed: " + e.Message); }.