I've just gotten started with creating a simple inventory extension for a web app and I've run into an issue where I'm having trouble updating the rows in a table for values that already exist in the Product column.
The method is pretty similar to the insert data method, which is working so I'm not exactly sure about what is going on. Here's the code that I have:
static void ReplaceInventory(string product, int qty)
{
using (SqlConnection con = new SqlConnection(
"Data Source=TestSQL;Initial Catalog=TestInv;User ID=tester;Password=passwordtest;"))
{
con.Open();
try
{
using (SqlCommand command = new SqlCommand(
"UPDATE Inventory SET Qty = @Qty WHERE Product = @Product", con))
{
command.Parameters.Add(new SqlParameter("@Qty", qty));
command.Parameters.Add(new SqlParameter("@Product", product));
command.ExecuteNonQuery();
}
}
catch
{
Console.WriteLine("Record not updated");
}
con.Close();
}
}
This works however:
static void AddInventory(string product, int qty)
{
using (SqlConnection con = new SqlConnection(
"Data Source=TestSQL;Initial Catalog=TestInv;User ID=tester;Password=passwordtest;"))
{
con.Open();
try
{
using (SqlCommand command = new SqlCommand(
"INSERT INTO Inventory VALUES(@Product, @Qty)", con))
{
command.Parameters.Add(new SqlParameter("Product", product));
command.Parameters.Add(new SqlParameter("Qty", qty));
command.ExecuteNonQuery();
}
}
catch
{
Console.WriteLine("Count not insert.");
}
con.Close();
}
}
Any help or pointers would be much appreciated!
@symbol incommand.Parameters.Add(new SqlParameter("@Qty", qty));andcommand.Parameters.Add(new SqlParameter("@Product", product));so both lines have "Qty" and "Product" as query parameter names, you have it that way in INSERT query which works.@product stringas the "key" to your product table. Are you absolutely sure that you got that right? Do you have a difference in spelling, or is there an extra space at the end of that string, either in your C# code or in the database? Strings as keys are a tricky business.....