Storing fields from a database in an array c#

喜夏-厌秋 提交于 2019-12-12 03:07:46

问题


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];
                        }
                    }
                }
            }
        }


来源:https://stackoverflow.com/questions/29402911/storing-fields-from-a-database-in-an-array-c-sharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!