Svetoslav
Svetoslav

Reputation: 99

How to get the database error when executing SqlCommand.ExecuteNonQuery in c#?

I have these statements:

SqlCommand sqlcmd = new SqlCommand("some query", "some db connection");
sqlcmd.ExecuteNonQuery();

How do I get the messages from the database when this query is executed?

For example if 2 rows are affected, I want the SQL Server message that says:

 1 row(s) affected
 1 row(s) affected

in the C# code. Or for example if there is a conflict with primary key, I mean I am trying to insert row with primary key that exists I want to receive the database error message which says : "Primary key duplicate".

Upvotes: 0

Views: 2444

Answers (1)

António Campos
António Campos

Reputation: 171

one of the possible solutions:

int rowsAffected = 0;
bool HasErrors = false;
try
  {
     SqlCommand sqlcmd = new SqlCommand("some query", "some db connection");
        rowsAffected= sqlcmd.ExecuteNonQuery();
  }
  catch (System.Exception ex)
  {
     HasErrors=true;
     MessageBox.Show(ex.message)
  }

  if (!HasErrors)
  {
     MessageBox.Show(rowsAffected.ToString() + " row(s) affected.");
  }

Upvotes: 5

Related Questions