IDbCommand.ExecuteNonQuery Method

Definition

Executes an SQL statement against the Connection object of a .NET data provider, and returns the number of rows affected.

C#
public int ExecuteNonQuery();

Returns

The number of rows affected.

Exceptions

The connection does not exist.

-or-

The connection is not open.

Examples

The following example creates an instance of the derived class, OleDbCommand, and then executes it. To accomplish this, the method is passed a string that is a SQL SELECT statement and a string to use to connect to the data source.

C#
static private void CreateOleDbCommand(
    string queryString, string connectionString)
{
    using (OleDbConnection connection = new
               OleDbConnection(connectionString))
    {
        connection.Open();
        OleDbCommand command = new
            OleDbCommand(queryString, connection);
        command.ExecuteNonQuery();
    }
}

Remarks

You can use the ExecuteNonQuery to perform catalog operations (for example, querying the structure of a database or creating database objects such as tables), or to change the data in a database without using a DataSet by executing UPDATE, INSERT, or DELETE statements.

Although the ExecuteNonQuery does not return any rows, any output parameters or return values mapped to parameters are populated with data.

For UPDATE, INSERT, and DELETE statements, the return value is the number of rows affected by the command. For all other types of statements, the return value is -1.

Applies to

Product Versions
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9, 10
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 2.0, 2.1