0

How can I know if data was inserted in the database successfully, or whether an error occurred when executing ExecuteNonQuery()?

con.Open();

SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "insert into DOCUMENT(NUM_D_ORDRE_DOC,ID_PERSONE,TYPE_DOC,PRIX_DOC,DATE_DE_MISE_EN_CHARGE,DATE_CREATION)values('"+TextBox1.Text+"','1','"+TextBox2.Text+"','"+TextBox4.Text+"','"+TextBox3.Text+"','"+ @DateTime.Now + "');";

cmd.ExecuteNonQuery();
con.Close();
CodeCaster
  • 147,647
  • 23
  • 218
  • 272
abdelhedi hlel
  • 2,903
  • 1
  • 16
  • 20
  • You can check with proper use of try catch block. – Divyang Desai Aug 03 '16 at 12:52
  • 2
    See also [Get affected rows on ExecuteNonQuery](http://stackoverflow.com/questions/10059158/get-affected-rows-on-executenonquery). Please read [ask] and try searching before asking a question. Also, go read about SQL injection and parameterize your queries. – CodeCaster Aug 03 '16 at 12:54

3 Answers3

3

You can check the return value of ExecuteNonQuery().

Like this:

int rowsAffected = cmd.ExecuteNonQuery();

It throws exception if any error occurs.

More info: ExecuteNonQuery Method

Romy Mathews
  • 797
  • 7
  • 13
1

This should answer your question:

For UPDATE, INSERT, and DELETE statements, the return value is the number of rows affected by the command. When a trigger exists on a table being inserted or updated, the return value includes the number of rows affected by both the insert or update operation and the number of rows affected by the trigger or triggers. For all other types of statements, the return value is -1. If a rollback occurs, the return value is also -1.

Source: https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executenonquery.aspx

manuzi1
  • 1,068
  • 8
  • 18
0

cmd.ExecuteNonQuery() will throw an exception if the insert fails for some reason.

If you're really paranoid, you can check the return value of the cmd.ExecuteNonQuery() method call and validate that it returns one (1) for the record that just got inserted.

Note: Consider using parameter binding instead of string concatenation to avoid subjecting yourself to SQL injection and simple quoting errors.

sstan
  • 35,425
  • 6
  • 48
  • 66