gpt4 book ai didi

c# - 如何知道查询是否成功?

转载 作者:可可西里 更新时间:2023-11-01 07:46:07 27 4
gpt4 key购买 nike

我如何知道以下 INSERT 查询是否成功?

MySqlConnection connection = new MySqlConnection(ConnectionString);
connection.Open();
MySqlCommand command = new MySqlCommand("INSERT INTO People (PersonName, dateAdded) VALUES (?name, NOW())", connection);
command.Parameters.Add(new MySqlParameter("name", Name));
MySqlDataReader Reader = command.ExecuteReader();

我尝试运行 Reader.Read() 但只返回一个空字符串。谢谢。

最佳答案

您改为使用 ExecuteNonQuery :

int affectedRows = command.ExecuteNonQuery();
if (affectedRows <= 0)
{
// Houston, we have a problem.
}

请记住,如果您对数据有触发器,它可能不会反射(reflect)您尝试INSERT 的实际行数:

You can use ExecuteNonQuery to perform any type of database operation, however any resultsets returned will not be available. Any output parameters used in calling a stored procedure will be populated with data and can be retrieved after execution is complete. For UPDATE, INSERT, and DELETE statements, the return value is the number of rows affected by the command. For all other types of statements, the return value is -1.

但是,一般来说,您会收到一个 MySqlException如果您的查询遇到错误。

关于c# - 如何知道查询是否成功?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9607302/

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