我很难从SQL数据库中删除一行,我没有收到任何错误,它似乎工作正常,但没有删除任何内容。当我运行代码时,它将输出“NAME已被删除”
感谢您的帮助。
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();
}
答案 0 :(得分:4)
删除参数周围的引号。同时从参数中删除@ -sign,将其添加到命令中。
Command.CommandText = "DELETE FROM Contacts WHERE [First Name] = @Name;";
Command.Parameters.AddWithValue("Name", DropDownList1.SelectedValue);
答案 1 :(得分:4)
您不需要带参数化查询的单引号。
答案 2 :(得分:2)
您的标准很可能无法满足。 (引用参数)所以没有记录被删除。
Command.ExecuteNonQuery();
返回记录计数的int。因此,您可以将此检查为零,以确保它已被删除。
答案 3 :(得分: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();
}