SQL Server Method to delete a row using C# and SQL is not working

6l7fqoea  于 2023-06-28  发布在  C#
关注(0)|答案(2)|浏览(118)

i am having issues with my method to delete a row, it is not working. I share my code to delete.

Method to delete a row:

public void DeleteProject(string projectNameDelete)
    {
        Conectarbd.Open();

        string query = "DELETE FROM ProjectsClipBoardManager WHERE projectName = @projectName";
        SqlCommand cmd = new SqlCommand(query, Conectarbd);
        cmd.Parameters.Add("@projectName", SqlDbType.VarChar);
        cmd.Parameters["@projectName"].Value = projectNameDelete;

        int rowsAffected = cmd.ExecuteNonQuery();
        Conectarbd.Close();
        

        if (rowsAffected > 0)
        {
            MessageBox.Show("La línea se ha eliminado exitosamente.");
        }
        else
        {
            MessageBox.Show("No se encontró ningun proyecto con el nombre especificado.");
            Conectarbd.Close();
        }

    }

When i run my program my code goes through the else of DeleteProject method and says "There are not projects with that name". Sorry if my english is not good

Trying to delete a row from SQL server using C#

zphenhs4

zphenhs41#

Try debugging step by step to see the value of "cmd" when you execute it. There might really not be an existing entry in your table that matches your "where" clause.

I dont see anything inherently wrong with the code.

You can try replacing your two lines of adding the parameter with this:

command.Parameters.AddWithValue("@projectName", projectNameDelete);

but I do suspect debugging and checking what your "cmd" actually sends to the DB will solve your issue.

zrfyljdw

zrfyljdw2#

I have run your code and it has successfully deleted a record.

The value you are trying to delete may not be found in the table.

  • Verify that within your ProjectsClipBoardManager table there is a record that contains this value in the projectName column.
  • Verifies that the string exactly matches the one found in the table, that there are no spaces, signs or different capital letters.

Note: It is recommended to delete one record per primary key because doing this for the projectName column will delete all records matching that value, and when you run it again you will no longer have any records with that value, and no rows will be affected.

相关问题