我有一个C#程序,试图将数据插入MySQL数据库。数据可能已经在数据库中,在这种情况下,它只会覆盖数据。 示例:
MySqlConection dbConnection = ...; // Setup connection
int numCustomersToUpdate = 3;
String query =
"INSERT INTO customer_regions (customer_id, region_id)
VALUES (1, 205), (2, 314), (3, 151) // 3 customers
ON DUPLICATE KEY UPDATE region_id = VALUES(region_id)";
MySqlCommand cmd = new MySqlCommand(query, dbConnection);
int rowsAffected = cmd.ExecuteNonQuery();
if (rowsAffected == numCustomersToUpdate)
{
// Data either did not exist before and was inserted,
// or already existed and overwritten
}
else
{
// Error inserting data
}
问题在于,如果数据被覆盖,则rowsAffected
为0,这被认为是错误。不管数据是被插入还是被覆盖,我如何认为它是成功的SQL执行?