如何使用c#读取MySql列

时间:2018-03-12 21:49:56

标签: c# mysql

在从MySql表中读取多行的一列时,我遇到了麻烦。

我的代码如下:

    public ObservableCollection<string> ReadFromColumn(string table, string column)
    {

        query = string.Format("SELECT DISTINCT {0} FROM {1};", column, table);

        if (this.OpenConnection() == true)
        {
            outColumn = new ObservableCollection<string>();
            //Create Command
            MySqlCommand cmd = new MySqlCommand(query, connection);
            //Create a data reader and Execute the command
            MySqlDataReader reader = cmd.ExecuteReader();
            reader.Read();
            for (int i = 0; i < reader.FieldCount; i++)
                outColumn.Add(reader[i].ToString());
            //Read the data and store them in the list

        }

        CloseConnection();

由于某些愚蠢的原因,我无法理解我只能从读者那里得到一条记录。在MySql中发送相同的查询会呈现10个实例的完整列表吗?

有什么想法吗?

2 个答案:

答案 0 :(得分:1)

您应该将结果集循环为:

While (reader.Read()) 
{  
    //Then you can read the values as
   //reader[0].ToString();

}

答案 1 :(得分:1)

你需要循环结果:

<html>
  <head></head>
  <body>
    <% if current_user.admin? %>
      <div class="container">
        <!-- form content  -->
      </div>
    <% else %>
      <div class="alert alert-danger">
        <strong>Access Denied.</strong> Page requires admin status.
      </div>
    <% end %>
  </body>
</html>