Tuesday, May 9, 2023

C# | ExecuteNonQuery

C# | What is the use of ExecuteNonQuery() in C#?


Method: SqlCommand.ExecuteNonQuery
Namespace: System.Data.SqlClient
Assembly: System.Data.SqlClient.dll

Executes a Transact-SQL statement against the connection and returns the number of rows affected.


private static void CreateCommand(string queryString, string connectionString)
    using (SqlConnection connection = new SqlConnection(connectionString))
        SqlCommand command = new SqlCommand(queryString, connection);

queryString: a string that is a Transact-SQL statement (such as UPDATE, INSERT, or DELETE)
connectionString: a string to use to connect to the data source

(1) ExecuteNonQuery() works with catalog operations (querying the structure of a database or creating database objects such as tables).
(2) ExecuteNonQuery() works to change the data in a database without using a DataSet by executing UPDATE, INSERT, or DELETE statements.
(3) ExecuteNonQuery() returns no rows.
(4) Any output or return parameter values mapped to parameters are populated with data.
(5) The return type is Int32
(6) For UPDATE, INSERT, and DELETE statements, the return value is the number of rows affected by the command.
(7) For all other types of statements, the return value is -1.
(8) 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.
(9) When SET NOCOUNT ON is set on the connection (before or as part of executing the command, or as part of a trigger initiated by the execution of the command) the rows affected by individual statements stop contributing to the count of rows affected that is returned by this method.
(10) If no statements are detected that contribute to the count, the return value is -1. If a rollback occurs, the return value is also -1.

No comments:

Post a Comment