Storing fields from a database in an array c#

2019-08-27 16:09发布

问题:

I am trying to store all fields from a column in my microsoft access database in an array. I am using OleDb but I don't really know how to go about doing this.

I know that I have to have a loop to go over the table the amount of times as there are rows in the table, but I don't know how to store the current field in the current index of the array. Any help would be greatly appreciated!

Here is a snippet of some of the code:

 string[] tasks;
 string sql = "SELECT [Task Name] FROM Tasks";  
 OleDbCommand cmd = new OleDbCommand(sql, conn);            
 OleDbDataReader dataReader = cmd.ExecuteReader();


 if (dataReader.HasRows)
 {
     for (int i = 1; i <= 10; i++)
     {
         //tasks[i] = current field in table
     }
 }

回答1:

Sounds like you want something like this?

        string[] tasks;
        string sql = "SELECT [Task Name] FROM Tasks";
        using (OleDbCommand cmd = new OleDbCommand(sql, conn))
        {
            using (OleDbDataReader dataReader = cmd.ExecuteReader())
            {
                List<object[]> list = new List<object[]>();
                if (dataReader.HasRows)
                {
                    while (dataReader.Read())
                    {
                        object[] oarray = new object[dataReader.FieldCount];
                        list.Add(oarray);
                        for (int i = 1; i <= dataReader.FieldCount; i++)
                        {
                            oarray[i] = dataReader[i];
                        }
                    }
                }
            }
        }