gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 15:54:25 24 4
gpt4 key购买 nike

我希望当有人想要从数据库中删除数据时。首先它检查数据是否存在,如果数据库中不存在数据,则显示未找到记录,那么我该如何做到这一点

        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...");

最佳答案

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

...
//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)
}
}
}

关于c# - 如何检查数据是否存在然后删除数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56577163/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com