为什么我的计数命令 mysql return 错误值 -1?

Why does my count command in mysql return wrong value -1?

我正在使用 gcloud mysql 并使用 c# 插入值和内容。 我正在尝试获取 table Categories_tbl 中的记录数量。我的代码是: 但是在执行 x 等于 -1 之后这是错误的。它会是什么?

MySqlCommand count_categories = new MySqlCommand(
  "SELECT COUNT(CategoryId) FROM Categories_tbl;", 
   connection);

x = count_categories.ExecuteNonQuery();

这不是 "NonQuery",这 查询,您想要的结果是:

x = count_categories.ExecuteScalar();

由于我不知道你的 x 是什么类型,你可能需要将其转换为正确的类型。

嗯,

count_categories.ExecuteNonQuery();

returns 有多少记录受到影响;您不调用 insertupdatedelete,所以您有 -1。改为

x = count_categories.ExecuteScalar();

执行查询和 return 单个结果。另一种(更罗嗦)的可能性

using (var reader = count_categories.ExecuteReader()) {
  if (reader.Read())
    x = Convert.ToInt32(reader[0]); // if you want int as a result
  else {
    // cursor is empty
  }
} 

编辑:如果你想阅读几条条记录,可以使用它,例如

List<Category> list = new List<Category>(); 

using (var reader = count_categories.ExecuteReader()) {
  while (reader.Read()) {
    //TODO: put the right syntax here
    Category category = new Category() {
      Name = Convert.ToString(reader["Name"]),
    };  

    list.Add(category);
  }
}