我有一个脚本连接自己的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());
}
为什么没有显示消息框?
答案 0 :(得分:1)
您需要使用ExecuteNonQuery()
对象的MySqlCommand
方法,该方法将返回受影响的行 - 我怀疑您正在寻找。 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!");
}
}
}