如何使用C#&删除SQL表记录SQL WHERE子句 [英] How to delete a SQL table record using C# & SQL WHERE clause

查看:164
本文介绍了如何使用C#&删除SQL表记录SQL WHERE子句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,



我想用C#删除sql表记录。我已经尝试了下面提到的代码片段,但它没有用。然而,该消息显示数据记录被删除!应该是它应该是。我在声明中也找不到问题。



我尝试了什么:



Hi All,

I want to delete a sql table record using C#. I already tried the below mentioned code snippet but it didn't work. However the message is showing 'Data Record Deleted!' as it should it be. I can't find an issue in the statement also.

What I have tried:

private void btnDeleteData_Click(object sender, EventArgs e)
       {
           try
           {

               SqlComm = new SqlCommand("DELETE FROM MyDataTable WHERE DataID='@DataID'", SqlConn);
               SqlComm.Parameters.AddWithValue("@DataID", txtDataID.Text);
               SqlComm.ExecuteNonQuery();
               MessageBox.Show("Data record deleted!", "DB Connection With App.Config", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);

               Clear();
               DisableButtons();
           }
           catch (Exception ex)
           {
               MessageBox.Show(ex.Message);
           }
       }





有人可以试着解决这个问题吗?



谢谢和问候,

Chiranthaka



Could someone please try to solve this matter?

Thanks and regards,
Chiranthaka

推荐答案

代码看起来不错,所以最多可能的事情是WHERE子句不匹配任何行。

首先检查命令影响的行数:ExecuteNonQuery返回:

The code looks OK, so the most likely thing is that the WHERE clause matches no rows.
Start by checking how many rows the command is affecting: the ExecuteNonQuery returns that:
SqlComm.Parameters.AddWithValue("@DataID", txtDataID.Text);
int deleted = SqlComm.ExecuteNonQuery();
MessageBox.Show(string.Format("{0} rows deleted.", deleted), "DB Connection With App.Config", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);

如果该值指示为零,则使用调试器确切检查txtDataId中的内容,并使用SSMS手动检查数据库是否存在完全匹配。

If that indicates zero, then use the debugger to check exactly what is in txtDataId and manually check the DB for exact matches using SSMS.


这篇关于如何使用C#&删除SQL表记录SQL WHERE子句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆