I have a database with some columns named UPC title Description and Quantity. i am trying to do a check to see if a UPC number already exists in the column and IF IT DOES then update the quantity of that entry by 1 here is what i have so far:
MySqlConnection connection = new MySqlConnection(MyConString);
connection.Open();
MySqlCommand command = connection.CreateCommand();
command.CommandText = "INSERT INTO tableName " +
"(upc, title, description, quantity) " +
"VALUES " +
"(@upc, @title, @description, @quantity)";
MySqlCommand upcCheck = connection.CreateCommand();
upcCheck.CommandText = "Select COUNT (*) FROM tableName WHERE " +
"(upc=@upc) LIMIT 1";
upcCheck.Parameters.AddWithValue("@upc", upc.Text); //Checks for duplicate UPCs
MySqlDataReader check = upcCheck.ExecuteReader();
if( check.Read() != false)
{
command.Parameters.AddWithValue("@quantity",++); //not sure how to word it right
}
command.Parameters.AddWithValue("@upc", upc.Text); //adding parameters SAFELY to the statement
command.Parameters.AddWithValue("@title", titlename);
command.Parameters.AddWithValue("@description", descname);
command.Parameters.AddWithValue("@quantity", "1");
MySqlDataReader result = command.ExecuteReader();
I’m just not sure how to word it to do the check.
UPDATE! Here is the working code.
MySqlConnection connection = new MySqlConnection(MyConString);
connection.Open();
MySqlCommand updatecommand = connection.CreateCommand();
updatecommand.CommandText = "UPDATE tableName Set quantity = quantity +1 " +
"WHERE upc = @upc";
updatecommand.Parameters.AddWithValue("@upc", upc.Text);
using (MySqlDataReader updateResult = updatecommand.ExecuteReader())
{
if (updateResult.RecordsAffected == 0)
{
affected = true;
}
else
{
affected = false;
}
}
if(affected == true)
{
MySqlCommand command = connection.CreateCommand();
command.CommandText = "INSERT INTO tableName " +
"(upc, title, description, quantity) " +
"VALUES " +
"(@upc, @title, @description, @quantity)";
command.Parameters.AddWithValue("@upc", upc.Text);
command.Parameters.AddWithValue("@title", titlename);//adding parameters SAFELY to the statement
command.Parameters.AddWithValue("@description", descname);
command.Parameters.AddWithValue("@quantity", "1");
MySqlDataReader result = command.ExecuteReader();
}
Although I’ve not worked specifically with MySqlDataReader, I would slightly change the queries around… the otherwise format (parameterization) you have for the insert is completely fine.
Although the ON DUPLICATE KEY UPDATE provided by Hristo is cool, you would be missing the other column elements for your record. I would change to..
** Dont know how the value / status will be returned from the MySqlDataReader, but
OTHERWISE, it was not on file.. continue with the rest of your SQL-insert command, we can overwrite the last command instance…