ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel

Executenonquery of SqlCommand in C# ado.net - Code Sample

Updated on June 14, 2016

1. Introduction

The ExecuteNonQuery method of the SQLCommand object is used to execute the DML statement on the Database. The DML (Data Manipulation Language) statement makes changes to the database. The Update statement is one such example as it modifies the existing data in the database. Have a look at the below picture:

Ado.Net ExecuteNonQuery
Ado.Net ExecuteNonQuery | Source

In the picture, you can observe that the ExecuteNonQuery method, when called, refers the SQL Statement stored in the CommandText property and executes that on the database object. The number of rows affected by the execution of DML statement is returned by the ExecuteNonQuery method of the SQLCommand Object. Let us explore this with an example.

After starting the VC# Console application, add the below piece of code at File starting (Program.cs):

//Sample 01: Required Name Space
using System.Data;
using System.Data.SqlClient;

2. Opening DB Connection

The Connection String is constructed first and this connection string connects to Pubs sample database. How do we form the connection string is already explained in the previous hub. A short note here is – DataSource represents where the database is located, Initial Catalog represents the name of the database, UserID and Password represent the authentication credentials to the database. Below is the code that creates the connection string and opens connection to the SQL Server database:

//Sample 02: Form the SQL Connection String and Open 
//           Connection Object.
string connection_string = "Data Source=(Local);Initial " + 
    "Catalog=Pubs; Persist Security Info=True;" +
    "User ID=sa;Password=rohith";

SqlConnection con = new SqlConnection(connection_string);
con.Open();

3. Executing DML Statement

The Data Manipulation statement is created and stored in the SQLCommand object. Note that the connection object created in the previous section is passed as the parameter to the constructor of the SqlCommand. The update statement updates the City Name of the authors who lives in Oakland. Below is code:

//Sample 03: Create SQL Command by supplying the 
//           con to the constructor
SqlCommand cmd = new SqlCommand("Update Authors set " +
    "city = 'Oakland.' where city = 'Oakland'", con);

Once the above command is ready with a valid DML statement (Update in this case) ExecuteNonQuery method is called. Have a look at the below depiction:

ExecuteNonQuery Return Value
ExecuteNonQuery Return Value | Source

The ExecuteNonQuery method is called on the cmd object constructed in code snippet 03. This method executes the Update statement on the SQL Server database and the result of executing the Update Query is stored in the Rows_affected variable. This variable is used to inform the user of an application to specify how many row or rows are affected by the execution of the update statement. Below is code:

//Sample 04: Execute the Query and Display the message
//           in the console window
int Rows_affected = cmd.ExecuteNonQuery();
System.Console.WriteLine("");
System.Console.WriteLine("");
System.Console.WriteLine("\t{0} Rows Affected", Rows_affected);

Below is the screen shot of console window output:

Program Output
Program Output | Source

4. Clean Up

The below code revert backs the modification to the original statement. This time, we change only the CommandText property of the SqlCommand object cmd. Once the CommandText is changed, the ExecuteNonQuery method is called again to revert back the change made by the previous database update statement. Below is the code for it:

//Sample 05: Revert back the Database records to Original
cmd.CommandText = "Update Authors set city = 'Oakland' " + 
    "where city = 'Oakland.'";
cmd.ExecuteNonQuery();

The complete code example is shown below:

using System;
using System.Collections.Generic;
using System.Text;

//Sample 01: Required Name Space
using System.Data;
using System.Data.SqlClient;

namespace ExecuteNonQuery
{
    class Program
    {
        static void Main(string[] args)
        {
            //Sample 02: Form the SQL Connection String and Open 
            //           Connection Object.
            string connection_string = "Data Source=(Local);Initial " + 
                "Catalog=Pubs; Persist Security Info=True;" +
                "User ID=sa;Password=rohith";

            SqlConnection con = new SqlConnection(connection_string);
            con.Open();

            //Sample 03: Create SQL Command by supplying the 
            //           con to the constructor
            SqlCommand cmd = new SqlCommand("Update Authors set " +
                "city = 'Oakland.' where city = 'Oakland'", con); 

            //Sample 04: Execute the Query and Display the message
            //           in the console window
            int Rows_affected = cmd.ExecuteNonQuery();
            System.Console.WriteLine("");
            System.Console.WriteLine("");
            System.Console.WriteLine("\t{0} Rows Affected", Rows_affected);

            //Sample 05: Revert back the Database records to Original
            cmd.CommandText = "Update Authors set city = 'Oakland' " + 
                "where city = 'Oakland.'";
            cmd.ExecuteNonQuery();
        }
    }
}

5. Closing Notes

Note that the sample application uses the Microsoft supplied sample database Pubs. You can search google with NorthWnd or Pubs Download to get the required database. Or, once you understand this hub, you can apply it on your own database.

Comments

    0 of 8192 characters used
    Post Comment

    • M K Paul profile image

      M K Paul 3 years ago from India

      It's long tht i hv seen something in C..I was a C/C++ programmer once a day..But now a full time mom...Nice to read article

    • sirama profile image
      Author

      sirama 3 years ago

      Thanks Paul.

    Click to Rate This Article