Little Programmer Little Programmer - 2 months ago 6
SQL Question

Is there a way to display an error message if the table is not updated?

I want to update a row in a table:

try
{
string sql ="UPDATE TableNAme SET FirstName ='John' WHERE ID = 123";

MySqlCommand command = new MySqlCommand(sql, connection);
connection.Open();

command.ExecuteNonQuery();
}
catch (Exception)
{
}
finally
{
connection.Close();
}


Based on the ID (key), it works perfectly if the ID was in the table, but if the ID doesn't exist in the table it shows no error message.

Is there a way that I can know if the ID was not found?

Answer

Actually ExecuteNonQuery returns the number of rows affected. You can make use of that:

int affectedRows = command.ExecuteNonQuery();

if (affectedRows == 0)
{
    // show error;
}
else
{
    // success;
}