I have a C# application which uses MySQL to insert data into a database. The application sometimes inserts data that is already in the DB. What is the best way to detect if there were any errors in this case?
I understand that ExecuteNonQuery() returns the number of rows affected, so if this is greater than 0, then that can be interpreted as a successful transaction. However if the data is already in the database, then the rows affected is 0, but this can also be considered a successful transaction since the data is in the DB.
string sql = @"INSERT my_table (field1, field2) VALUES (@value1, @value2);"
MySqlCommand cmd = new MySqlCommand(sql, connection);
// Execute
int rowsAffected = cmd.ExecuteNonQuery();
if (rowsAffected > 0)
{
// Query was successful
}
else
{
// Query *may* have been successful
}
UPSERTinstead? dev.mysql.com/doc/refman/5.7/en/insert-on-duplicate.html That might return a more useful count for you