2

我很难从 SQL 数据库中删除一行,我没有收到任何错误,而且它似乎工作正常,但没有删除任何内容。当我运行代码时,它将输出“名称已被删除”

谢谢你的帮助。

SqlConnection conn = new SqlConnection();
conn.ConnectionString = "Data Source=(LocalDB)\\v11.0;AttachDbFilename=|DataDirectory|\\MyDB.mdf;Integrated Security=True";

try
{
    conn.Open();
    SqlCommand Command = conn.CreateCommand();
    Command.CommandText = "DELETE FROM Contacts WHERE [First Name] = '@Name';";
    Command.Parameters.AddWithValue("@Name", DropDownList1.SelectedValue);
    Command.ExecuteNonQuery();
    TextBox1.Text = DropDownList1.SelectedValue + " Has Been Deleted";
}
catch (Exception ex)
{
    TextBox1.Text = "Nope";
}
finally
{
    conn.Close();
} 
4

4 回答 4

4

删除参数周围的引号。还要从参数中删除 @-sign,将其添加到命令中。

Command.CommandText = "DELETE FROM Contacts WHERE [First Name] = @Name;";
Command.Parameters.AddWithValue("Name", DropDownList1.SelectedValue);
于 2013-06-05T19:25:18.940 回答
4

参数化查询不需要单引号。

于 2013-06-05T19:25:39.287 回答
2

您的标准很可能没有得到满足。(参数周围的引号)所以没有记录被删除。

Command.ExecuteNonQuery();

返回记录计数的 int。因此,您可以根据零检查它以确保它已被删除。

于 2013-06-05T19:24:43.707 回答
1

下面详细介绍几件事:

SqlConnection conn = new SqlConnection();
conn.ConnectionString = "Data Source=(LocalDB)\\v11.0;AttachDbFilename=|DataDirectory|\\MyDB.mdf;Integrated Security=True";

try
{
   conn.Open();
   SqlCommand Command = conn.CreateCommand();
   Command.CommandText = "DELETE FROM Contacts WHERE [First Name] = Name;"; // You don't need the '' or the '@' in your parameter name.
   Command.Parameters.AddWithValue("@Name", comboBox1.SelectedValue);
   if (Command.ExecuteNonQuery() > 0)  //  Add a conditional here that checks for > 0 and THEN set your validation text.
      textBox1.Text = comboBox1.SelectedValue + " Has Been Deleted";
}

catch (Exception ex)
{
   textBox1.Text = "Nope";
}

finally
{
   conn.Close();
} 
于 2013-06-05T19:37:33.850 回答