简体   繁体   English

如何从列表框中删除数据库中的单个项目?

[英]How to remove single item in database from a listbox?

How to remove single item in database? 如何删除数据库中的单个项目? When I click on remove button my code removes all items that are same as the selectedItem in listbox. 当我单击删除按钮时,我的代码将删除与列表框中的selectedItem相同的所有项目。 eg If I choose to remove CocaCola from my listbox I want that it removes that single CocaCola item in database not all CocaCola items. 例如,如果我选择从列表框中删除可口可乐,则希望它删除数据库中的单个可口可乐项目,而不是所有可口可乐项目。

my code: 我的代码:

conn.Open();
SqlCommand cmd = new SqlCommand("delete from Products Where Product ='"+lstProducts.SelectedItem+"'", conn);
cmd.ExecuteNonQuery();
conn.Close();

If it doesn't matter which rows remain you can use TOP(1) : 如果剩下的行没关系,则可以使用TOP(1)

DELETE TOP (1)
FROM  Products 
Where Product = @Product

Note that you should use sql parameters instead of string concatanation to prevent sql injection and other less serious issues. 请注意,应该使用sql参数而不是字符串连接来防止sql注入和其他不太严重的问题。

MSDN : MSDN

When TOP is used with DELETE, the referenced rows are not arranged in any order and the ORDER BY clause can not be directly specified in this statement. 当TOP与DELETE一起使用时,引用的行不会以任何顺序排列,并且该语句中不能直接指定ORDER BY子句。 If you need to use TOP to delete rows in a meaningful chronological order, you must use TOP together with an ORDER BY clause in a subselect statement. 如果需要使用TOP以有意义的时间顺序删除行,则必须在subselect语句中将TOP与ORDER BY子句一起使用。 See the Examples section that follows in this topic. 请参阅本主题后面的“示例”部分。 TOP cannot be used in a DELETE statement against partitioned views. TOP不能在针对分区视图的DELETE语句中使用。

Acc. 加。 to the TOP(1) : TOP(1)

For backward compatibility, the parentheses are optional in SELECT statements. 为了向后兼容,括号在SELECT语句中是可选的。 We recommend that you always use parentheses for TOP in SELECT statements for consistency with its required use in INSERT, UPDATE, MERGE, and DELETE statements in which the parentheses are required . 我们建议您始终对SELECT语句中的TOP使用括号,以使其在需要括号的INSERT,UPDATE,MERGE和DELETE语句中所需的用法保持一致。

You can try to use TOP like this: 您可以尝试像这样使用TOP:

SqlCommand cmd = new SqlCommand("delete top (1) from Products Where Product ='"+lstProducts.SelectedItem+"'", conn);
cmd.ExecuteNonQuery();

Also your code is prone to SQL Injection. 另外,您的代码也易于进行SQL注入。 You can use parameterized query to get rid of it. 您可以使用参数化查询来摆脱它。

为此,您需要具有带有外键“唯一”的“产品”列,否则,您需要传递ID或另一个唯一列。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM