【问题标题】:mysql select command in C# with dynamic column namesC#中的mysql选择命令,带有动态列名
【发布时间】:2015-08-13 09:52:29
【问题描述】:

我在 C# 中有一个字符串,它具有如下所示的表的列名

shown_itemsName = "billno,department,date,subtotal,tea,coffee";

我想在 dataGridView 中显示一个表,其中列名在字符串 (shown_itemsName) 中,但是当我编写 sql 查询时

cmdDataBase.CommandText = "select @shown_itemsName from employee.transaction where department = @department AND MONTH(date) = @month_ AND YEAR(date) = @year_";
cmdDataBase.Parameters.AddWithValue("@shown_itemsName", shown_itemsName);
cmdDataBase.Parameters.AddWithValue("@department", this.department.Text);
cmdDataBase.Parameters.AddWithValue("@month_", this.dateTimePicker1.Value.Month);
cmdDataBase.Parameters.AddWithValue("@year_", this.dateTimePicker1.Value.Year);

我得到一个只有 1 列和 4 行的表格,单元格值为 billno、department、date、subtotal、tea、coffee 和该列的标题也是相同的字符串。 而我应该得到 6 列和 4 行的结果,以“,”分隔的子字符串作为列名

【问题讨论】:

标签: c# mysql datagridview


【解决方案1】:

您不能添加带有参数的新列。如果它是动态的,您别无选择,只能每次编写查询并对其执行 CommandType.Text 命令。

对于每个请求,您必须:

cmdDataBase.CommandText = "select " + shown_itemsName + " from employee.transaction where department = @department AND MONTH(date) = @month_ AND YEAR(date) = @year_";

cmdDataBase.Parameters.AddWithValue("@department", this.department.Text);
cmdDataBase.Parameters.AddWithValue("@month_", this.dateTimePicker1.Value.Month);
cmdDataBase.Parameters.AddWithValue("@year_", this.dateTimePicker1.Value.Year);

using(var reader = cmdDataBase.ExecuteReader()) {
    while(reader.Read()) {
        // ...
    }
    reader.Close();
}

【讨论】:

  • string shown_itemsName 每次用户选择部门和日期时都会更新。所以我想使用那个部门和日期作为选择命令的输入。
  • 是的,因此您应该手动构建 sql 查询并在其上执行文本命令。您不能使用存储过程或准备好的语句。我已经编辑了答案以使其更清晰
  • 我没有刷新页面并写了该评论,但现在我在看到您的回答后删除了该评论
  • 我不知道该怎么说谢谢。它的工作方式与我想要的完全一样。我被困在这件事上 4 到 5 小时。非常感谢 tafia
  • 谢谢你告诉我我不知道我也必须这样做
猜你喜欢
  • 2012-07-26
  • 1970-01-01
  • 2014-10-14
  • 1970-01-01
  • 2023-03-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多