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

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 fine if the identifier was in the table, but if the identifier does not exist in the table, it does not show an error message.

Is there a way to find out if an ID is found?

+4
source share
3 answers

Actually ExecuteNonQueryreturns the number of rows affected. You can use this:

int affectedRows = command.ExecuteNonQuery();

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

First of all, if you are connecting to (Microsoft) SQL Server , you need to use both - and not . SqlConnection SqlCommandMySqlConnectionMySqlCommand

- - ExecuteNonQuery() int, - , 0, .

int rowsAffected = command.ExecuteNonQuery();

if (rowsAffected == 0)
{
    // show message - no rows updated
}
+4

SET NOCOUNT ON, . SET NOCOUNT - OFF, .

https://msdn.microsoft.com/en-us/library/ms189837.aspx

- SQL SET NOCOUNT { ON | OFF }:

// Will return always 0  if SET NOCOUNT is ON.!!!
int affectedRows = command.ExecuteNonQuery();  

@@ROWCOUNT (Transact-SQL) https://msdn.microsoft.com/en-CA/library/ms187316.aspx

2 , ROWCOUNT_BIG https://msdn.microsoft.com/en-ca/library/ms181406.aspx

!!!! @@ROWCOUNT , SET NOCOUNT . https://msdn.microsoft.com/en-us/library/ms189837.aspx

SQL

      USE AdventureWorks2012;  
      GO  

      UPDATE HumanResources.Employee   
      SET JobTitle = N'Executive'  
      WHERE NationalIDNumber = 123456789  

      IF @@ROWCOUNT = 0  
      PRINT 'Warning: No rows were updated';  
      GO  

SQL .

The return value will be incorrect if SET NOCOUNT is enabled.

I think -1 or 0

+1
source

All Articles