如何检查数据是否存在然后删除数据

时间:2019-06-13 09:12:59

标签: c# mysql

我希望当有人想要从数据库中删除数据时,首先它会检查是否存在数据(如果数据库中不存在数据),表明没有找到记录,所以我该怎么做

        Console.WriteLine("Enter ID card No or Phone No to Delete");
        Double inputt = Convert.ToDouble(Console.ReadLine());

        MySqlConnectionStringBuilder conn_string = new MySqlConnectionStringBuilder();
        conn_string.Server = "localhost";
        conn_string.UserID = "root";
        conn_string.Password = "DynaSoft123@";
        conn_string.Database = "directory";

        string Query = "delete from directory.userdata where IdCardNo='" + inputt + "';";

        MySqlConnection MyConn2 = new MySqlConnection(conn_string.ToString());
        MySqlCommand MyCommand2 = new MySqlCommand(Query, MyConn2);

        MySqlDataReader MyReader2;
        MyConn2.Open();
        MyReader2 = MyCommand2.ExecuteReader();
        Console.WriteLine("Data Deleted Successfully...");

1 个答案:

答案 0 :(得分:0)

您应该使用ExecuteNonQuery,而不是ExecuteReader()。您不必检查数据是否存在,如果没有delete则什么也不做。

...
//DONE: wrap IDisposable into using
using (MySqlConnection MyConn2 = new MySqlConnection(conn_string.ToString())) {
  MyConn2.Open();

  //DONE: make sql readable
  //DONE: make sql paramterized
  string Query = 
    @"delete 
        from directory.userdata 
       where IdCardNo = @prm_IdCardNo";

  using (MySqlCommand MyCommand2 = new MySqlCommand(Query, MyConn2)) {
    //TODO: Add("@prm_IdCardNo", RDBMSType).Value = is a better option
    MyCommand2.Parameters.AddWithValue("@prm_IdCardNo", inputt);

    // ExecuteNonQuery - just execute, we have nothing to read
    int affected = MyCommand2.ExecuteNonQuery();

    // If you want to know if table has been modified
    if (affected > 0) {
      // Some records are affected (deleted)
    }
  } 
}