简体   繁体   English

如何从表中删除单个条目

[英]How can I delete a single entry from a table

I have a listbox with usernames, and a remove button I want the selected a user (with all entered data associated with that user) to be deleted when the remove button is clicked. 我有一个带有用户名的列表框和一个删除按钮,我希望在单击删除按钮时删除所选的用户(与该用户关联的所有输入数据)。

My code 我的密码

SqlConnection con = new SqlConnection("Data Source=JAMES-PC\\SQLEXPRESS;Initial Catalog=staff;Integrated Security=True");
con.Open();

string sql = @"DELETE FROM staff1;";
SqlCommand cmd = new SqlCommand(sql, con);
cmd.ExecuteNonQuery();
con.Close();

this code deletes the whole table. 此代码将删除整个表。

How can I just delete the selected user? 如何删除所选的用户?

You need a WHERE clause to select the required record. 您需要一个WHERE子句来选择所需的记录。 You have to get the username of the selected user to be deleted and pass it to @UserName parameter. 您必须获取要删除的所选用户的用户名,并将其传递给@UserName参数。

 var userName = (listBox.SelectedItem as DataRowView)["UserName"].ToString();
 string sql = @"DELETE FROM staff1 WHERE Username = @UserName;";

 SqlCommand cmd = new SqlCommand(sql, con);
 cmd.Parameters.AddWithValue("@UserName",useName);

 cmd.ExecuteNonQuery();
 con.Close();

See this thread on how to use parameters in the SQL. 有关如何在SQL中使用参数的信息,请参见此线程

When you execute a delete query, in order to delete only 1 row from the table you need to add a WHERE clause. 当执行删除查询时,为了只删除表中的1行,您需要添加WHERE子句。

Based on the comments the workflow should be something like: you click on a delete button, you send the name of the staff you want to delete to the command, which looks like: 根据注释,工作流应类似于:单击删除按钮,然后将要删除的人员名称发送给命令,如下所示:

 string sql = @"DELETE FROM staff1 where Name=@Name;";

 SqlCommand cmd = new SqlCommand(sql, con);
 cmd.Parameters.AddWithValue("@Name","NameReceivedFromList");

 cmd.ExecuteNonQuery();
 con.Close();

When you are deleting you should remember to add a Where clause, it is actually very powerfull here is some examples that will get you started 删除时,请记住添加一个Where子句,它实际上非常强大,这里有一些示例可以帮助您入门

The following query will delete only one element 以下查询将仅删除一个元素

DELETE FROM Table WHERE Table.PrimaryField = Value

The following query will delete all items that matches 以下查询将删除所有匹配的项目

DELETE FROM Table WHERE Table.Field = Value

You can also have a join in your delete statement for more complex delete queries 您还可以在delete语句中加入联接,以进行更复杂的删除查询

DELETE A FROM Table A 
INNER JOIN TableB B ON A.Key = B.Key
WHERE B.PrimaryField = Value

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

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