将数据库中的字段存储在数组C#中 [英] Storing fields from a database in an array c#

查看:110
本文介绍了将数据库中的字段存储在数组C#中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将Microsoft Access数据库中某个列中的所有字段存储在一个数组中.我正在使用OleDb,但我真的不知道该怎么做.

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

推荐答案

听起来像您想要这样的东西吗?

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

这篇关于将数据库中的字段存储在数组C#中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆