No Messagebox showing

本文关键字:showing Messagebox No | 更新日期: 2023-09-27 18:27:41

我有一个脚本,它将自己与mysql服务器连接,并在按下按钮时进行sql查询。

我的代码:

try
{
    MySqlConnection c = new MySqlConnection("Server=****;Database=*****;Uid=****;Pwd=y u no want to know ma pw;");
    MySqlCommand cmd = new MySqlCommand("DELETE FROM users WHERE username = '" + textBox1.Text + "'", c);
    MySqlDataReader myReader;
    c.Open();
    myReader = cmd.ExecuteReader();
    int cnt = 0;
    while(myReader.Read())
    {
        cnt = cnt + 1;
    }
    if (cnt == 1)
    {
        MessageBox.Show("Benutzer erfolgreich entfernt, Sir!");
    }
}
catch(Exception ex)
{
    MessageBox.Show("Benutzer konnte nicht entfernt werden.'n'n" +  ex.ToString());
}

为什么不显示消息框?

No Messagebox showing

您需要使用MySqlCommand对象的ExecuteNonQuery()方法,该方法将返回受影响的行——我怀疑您正在查找该行。DELETE语句不会返回结果集,只返回受影响的记录。

 using(MySqlConnection c = new MySqlConnection("Server=**;Database=***;Uid=**;Pwd=**;"))
   {
     using (MySqlCommand cmd = new MySqlCommand("DELETE FROM users WHERE username = @name"))
     {
         var userParam = new MySqlParameter();
         userParam.Name = "@name";
         userParam.Value = textbox1.Text;
         cmd.Parameters.Add(userParam);
         c.Open();
         var recordsAffected = cmd.ExecuteNonQuery();
         c.Close();
         if (recordsAffected == 1)
         {
            MessageBox.Show("Benutzer erfolgreich entfernt, Sir!");
         }
       }
     }