How can I get an error message that happens when using ExecuteNonQuery()?

前端 未结 8 1162
误落风尘
误落风尘 2020-12-06 04:59

I am executing a command in this way :

var Command = new SqlCommand(cmdText, Connection, tr);

Command.ExecuteNonQuery();

In the command th

8条回答
  •  萌比男神i
    2020-12-06 05:07

    Only high severity errors will be thrown back in ExecuteNonQuery. There is another scenario that I have observed with OdbcCommand.ExecuteNonQuery() method. May be this is true for SqlCommand.ExecuteNonQuery() as well. If the SQL contained in the CommandText property is a single statement (Example: INSERT INTO table (col1,col2) VALUES (2,'ABC'); ) and if there is a foreign key violation or primary key violation in the above statement ExecuteNonQuery will throw an exception. However, if your CommandText is a batch where you have more than one SQL Statements seperated by semi colon (Like Several INSERTS or UPDATES) and if one of them fails ExecuteNonQuery does not throw an exception back. You need to be explicitly checking for the number of records affected returned by the method. Simply putting the code in a try{}Catch{} wont help.

提交回复
热议问题