A Closer Look at ADO.NET: The Command Object - The ExecuteNonQuery() Method (DELETE Data)
(Page 4 of 5 )
In the following code example I use the ExecuteNonQuery() method to delete the newly entered record and then count how many records are in the table. Note that before we entered the above record, the table had only 14 records; after we delete the record, the table once again holds 14 records.
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 = "DELETE FROM jobs WHERE job_desc = 'Technical Writer'";
try
{
SqlConn1.Open();
Console.WriteLine("Rows Effected: " +
SqlComm1.ExecuteNonQuery());
SqlComm1.CommandText = "SELECT COUNT(*) FROM Jobs";
Console.WriteLine("The jobs table contains " +
SqlComm1.ExecuteScalar().ToString() + " Rows");
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
// here we call the Close() method to close the Connection
SqlConn1.Close();
Console.ReadLine();
}
}
}
}

This time we have assigned the property CommandText the string value (the T-SQL Statement) "DELETE FROM jobs WHERE job_desc = 'Technical Writer'" which deletes the record we just inserted into the table. After we called the ExecuteNonQuery() method, we assigned a new text to the CommandText property of the SqlComm1 object, which again counts how many records in the table. Now, let's learn how to use a stored procedure.
Next: Creating and Executing a Stored Procedure >>
More Database Code Articles
More By Michael Youssef