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

标签 c# mysql

我如何知道以下 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/

相关文章:

php - 计算 WordPress 中的单词出现次数

MySQL 表文件名编码

mysql - 如何调用mysql中的存储过程?

c# - 使用 WebClient 在 Unity3d 中下载大文件

c# - 只读的属性,但只能在类之外

c# - 任意定界符/转义字符处理的最佳算法是什么?

c# - 如何获取更新剪贴板的应用程序的进程ID或名称?

c# - 我可以将 long 转换为 int 吗?

php - 如何从 mysql 获取数据(从最后到第一个顺序)并在 JSON php 中显示?

mysql - PHP session 不会转移到其他页面