Learn ASP.NET Core 2 and Angular 6 in October 2018. Instructor-led online courses by Bipin Joshi. Read more...
Instructor-led Online Courses by Bipin Joshi : ASP.NET Core | Angular | Design Patterns
Registration open for October 2018 batches. Read more here.

<%@ Page %>

ADO.NET Series - Executing Action Queries

Introduction

In the previous article of the series we saw how to execute SELECT queries using SqlConnection, SqlCommand and SqlDataReader classes. In this part we will see how to execute action queries like INSERT, UPDATE and DELETE using SqlCommand class.

Example

//declare connection,command
SqlConnection cnn;
SqlCommand cmd;
//create connection
cnn=new SqlConnection
("your_connection_string");
cmd=new SqlCommand();
//open connection
cnn.Open();
//set command properties
cmd.Connection=cnn;
cmd.CommandText="insert into employees
(lastname,firstname) 
values('lastname1','firstname1')";
//fire the query
cmd.ExecuteNonQuery();
//close connection
cnn.Close();

Explanation

The code is straight forward. First, we open a connection with the database as usual. Next, we create an instance of SqlCommand object. We set Connection property to the SqlConnection we created before. We also set the CommandText property to required query (INSERT in this case). We then execute the query using ExecuteNonQuery() method of the SqlCommand class. Note that since our query is not returning any results we used ExecuteNonQuery() method and not ExecuteReader() method as in previous article. The ExecuteNonQuery() method returns an integer the indicated the number of rows affected by the query. We then close the database connection as before.

In our example we used SQL statement as the action query. You can also use stored procedure instead.


Bipin Joshi is a software consultant, trainer, author and spiritual yoga mentor having 23+ years of experience in software development. He teaches private online courses in ASP.NET Core and Angular to individuals and small groups. He is a published author and has authored or co-authored books for Apress and Wrox press. Having embraced the Yoga way of life he also teaches Ajapa Yoga to interested individuals. To know more about him click here.

He will be teaching ASP.NET Core 2.1 and Angular 6.1 in October 2018. Click here for his online course schedule and more details.

Get connected : Twitter  Facebook  Google+  LinkedIn

Posted On : 11 May 2003


Tags : ADO.NET Data Access SQL Server