SQL delete command?

Viewed 79256

I am having trouble with a simple DELETE statement in SQL with unexpected results , it seems to add the word to the list??. Must be something silly!. but i cannot see it , tried it a few different ways. All the same result so quite confused.

public void IncludeWord(string word)
{
    // Add selected word to exclude list
    SqlConnection conn = new SqlConnection();
    String ConnectionString = "Data Source = dev\\SQLEXPRESS ;" + "Initial Catalog=sml;" + "User id=** ;" + "Password =*;" + "Trusted_Connection=No";

    using (SqlConnection sc = new SqlConnection(ConnectionString))
    {
        try
        {
            sc.Open();

            SqlCommand Command = new SqlCommand(
               "DELETE FROM excludes WHERE word='@word'" +
                 conn);


           Command.Parameters.AddWithValue("@word", word);  
            Command.ExecuteNonQuery();
        }
        catch (Exception e)
        {
            Box.Text = "SQL error" + e;
        }
        finally
        {
           sc.Close();
        }
        ExcludeTxtbox.Text = "";

       Box.Text = " Word : " + word + " has been removed from the Exclude List";

        ExcludeLstBox.AppendDataBoundItems = false;
        ExcludeLstBox.DataBind();
    }
7 Answers

You can also try the following if you don't have access to some of the functionality prescribed above (due, I believe, to older versions of software):

using (var connection = _sqlDbContext.CreatSqlConnection())
{
    using (var sqlCommand = _sqlDbContext.CreateSqlCommand())
    {
        sqlCommand.Connection = connection;
        sqlCommand.CommandText = $"DELETE FROM excludes WHERE word = @word";
        sqlCommand.Parameters.Add(
                            _sqlDbContext.CreateParameterWithValue(sqlCommand, "@word", word));
        connection.Open();
        sqlCommand.ExecuteNonQuery();
    }
}
...

I'm an associate dev. Hence the "I believe" above.

Related