A Closer Look at ADO.NET: The Command Object - The ExecuteNonQuery() Method (INSERT Data)
(Page 3 of 5 )
In the following code example I use the ExecuteNonQuery() method to insert a new record into the jobs table. Let's take a look at the code.
using System;
// reference to the namespace that contains most
// of the classes that form the ADO.NET Architecture
using System.Data;
// referene to the namespace of the SQL Server .NET Data provider
using System.Data.SqlClient;
namespace AdoApp
{
class Class1
{
static void Main(string[] args)
{
SqlConnection SqlConn1 = new SqlConnection();
SqlConn1.ConnectionString = "Server=(local);Database=pubs;User ID=sa;Password=;";
// creating and initializing the SqlCommand Object
SqlCommand SqlComm1 = new SqlCommand();
SqlComm1.Connection = SqlConn1;
SqlComm1.CommandType = CommandType.Text;
SqlComm1.CommandText = "INSERT INTO jobs(job_desc,min_lvl,max_lvl)" + "VALUES('Technical Writer',25,100)";
try
{
SqlConn1.Open();
Console.WriteLine("Rows Effected: " +
SqlComm1.ExecuteNonQuery().ToString());
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
// here we call the Close() method to close the Connection
SqlConn1.Close();
Console.ReadLine();
}
}
}
}
Here's what you get when you run this code:

This time what we have changed the text of the command through the SqlComm1.CommandText property assignment, and we have used the method ExecuteNonQuery() to insert a new record into the jobs table. The ExecuteNonQuery() method, as its name implies, executes non query SQL Statements. This means that you can use it to execute INSERT, UPDATE, DELETE and CREATE statements, and the method returns the number of rows that have been affected by executing the text of the command. So in your example the CommandText property has the T-SQL Statement INSERT INTO jobs(job_desc,min_lvl,max_lvl) VALUES('Technical Writer',25,100), which inserts a record into the Jobs table. Let's delete our new entry.
Next: The ExecuteNonQuery() Method (DELETE Data) >>
More Database Code Articles
More By Michael Youssef