How to delete records with SqlCommand

This code shows you how to delete records with an SQL statement and get the number of records deleted returned back as an integer.

SqlConnection con = new SqlConnection(ConfigurationSettings.AppSettings["con"]);
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "DELETE FROM EmployeesCopy WHERE TitleofCourtesy='Mr.'";
cmd.Connection = con;
con.Open();
int numberDeleted = cmd.ExecuteNonQuery();
Response.Write(numberDeleted.ToString() + " employees were deleted.<br>");
// use this instead of the above line if we're in a windows form rather than an ASP.NET page
//MessageBox.Show(numberDeleted.ToString() + " employees were deleted.<br>");
con.Close();

You might also like...

Comments

Edward Tanguay Edward Tanguay updates his personal web site tanguay.info weekly with code, links, quotes and thoughts on web development. Sign up for the free newsletter.

Contribute

Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“It works on my machine.” - Anonymous