Quote:
string cmdInsert = @"INSERT INTO SoldProducts (BookName, Amount, Price) Values('" + Convert.ToString(r.Cells[0]) + "', '" + Convert.ToString(r.Cells[1]) + "', '" + Convert.ToString(r.Cells[4]) + "')";
Not like that!
Your code is vulnerable to
SQL Injection[
^].
NEVER use string concatenation to build a SQL query.
ALWAYS use a parameterized query.
Everything you wanted to know about SQL injection (but were afraid to ask) | Troy Hunt[
^]
How can I explain SQL injection without technical jargon? | Information Security Stack Exchange[
^]
Query Parameterization Cheat Sheet | OWASP[
^]
You already know how to use parameters - you've done it in the
UPDATE
query. So why haven't you done the right thing here?
As to your question, all you need to do is execute the
UPDATE
command and check the number of rows affected. If it doesn't affect any rows, then execute an
INSERT
command.
using (var command = new OleDbCommand("UPDATE SoldProducts SET Amount = Amount + @Amount WHERE BookName = @BookName", connection))
{
command.Parameters.AddWithValue("@Amount", newAmount);
command.Parameters.AddWithValue("@BookName", bookName);
int rowsAffected = command.ExecuteNonQuery();
if (rowsAffected == 0)
{
command.Parameters.Clear();
command.CommandText = "INSERT INTO SoldProducts (BookName, Amount, Price) VALUES (@BookName, @Amount, @Price)";
command.Parameters.AddWithValue("@BookName", bookName);
command.Parameters.AddWithValue("@Amount", newAmount);
command.Parameters.AddWithValue("@Price", price);
command.ExecuteNonQuery();
}
}