SQL删除行查询 [英] SQL Delete row query
问题描述
我已经在下面编写了这段小代码,以从数据库中删除一条记录:
Hi I have wrote this small piece of code below to delete a record from a database:
private void button2_Click(object sender, RoutedEventArgs e)
{
conn.Open();
SqlCommand sc = new SqlCommand("DELETE FROM dbo.Food_Items WHERE Food_Name = "+textBox2.Text+"", conn);
sc.ExecuteNonQuery();
conn.Close();
}
如果我替换查询的textBox2部分并将其替换为一个单词,则该查询工作正常.但是,当我在一个文本框中放入按卸妆按钮时,它会抛出此异常:
无效的列名"Beans".
Beans是我在textBox中键入的单词.我无法为自己的一生而思考为什么这行不通.我确定这是我输入的简单内容,但看不到!
一切帮助将不胜感激:)
The query works perfectly fine if I replace the textBox2 section of the query and replace it with a word. But when I put in a text box and press remover it throws this exception:
Invalid column name ''Beans''.
Beans being the word I have typed into the textBox. I can not for the life of me think why this won''t work. Im sure it''s something simple that I''ve typed but I can''t see it!
Any help will be appreciated cheers :)
推荐答案
您必须逃脱它,您丢失了''.
来自
You have to escape it, you are missing '' .
From
SqlCommand sc = new SqlCommand("DELETE FROM dbo.Food_Items WHERE Food_Name = "+textBox2.Text+"", conn);
致
To
SqlCommand sc = new SqlCommand("DELETE FROM dbo.Food_Items WHERE Food_Name = '"+textBox2.Text+"'", conn);
甚至更好地使用 SqlParameter [ ^ ]
Or even better use SqlParameter[^]
这篇关于SQL删除行查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!