带有动态列名的C#中的mysql select命令

时间:2015-08-13 09:52:29

标签: c# mysql datagridview

我在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行作为结果与“,”分隔的子串作为列名

1 个答案:

答案 0 :(得分:0)

您无法添加带参数的新列。如果它是动态的,你不能选择,而是每次都编写查询并在其上执行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();
}