将结果集从OleDbDataReader转换为列表

时间:2010-11-03 17:09:44

标签: c# .net oledbdatareader

考虑连接到SQL Server 2008数据库并运行SQL SELECT语句的Winforms应用程序:

string myConnectionString = "Provider=SQLOLEDB;Data Source=hermes;Initial Catalog=qcvaluestest;Integrated Security=SSPI;";

string mySelectQuery = "SELECT top 500 name, finalconc from qvalues where rowid between 0 and 25000;";

OleDbConnection myConnection = new OleDbConnection(myConnectionString);

OleDbCommand myCommand = new OleDbCommand(mySelectQuery, myConnection);

myCommand.Connection.Open();

OleDbDataReader myReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection);

如何将查询结果读入列表?

3 个答案:

答案 0 :(得分:2)

假设您已经定义了类似

的类
class MyData
{
    public string Name {get; set;}
    public int FinalConc {get; set;} // or whatever the type should be
}

您将遍历查询结果以加载列表。

List<MyData> list = new List<MyData>();
while (myReader.Read())
{
    MyData data = new MyData();
    data.Name = (string)myReader["name"];
    data.FinalConc = (int)myReader["finalconc"]; // or whatever the type should be
    list.Add(data);
}

// work with the list

如果您只需要其中一个给定字段,则可以放弃类定义,只需要List<T>,其中T是您要保留的字段的类型。

答案 1 :(得分:2)

您可以尝试一些事情(为方便起见进行调整):

public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
}

List<Person> dbItems = new List<Person>();

while(myReader.Read())
{
   Person objPerson = new Person();

   objPerson.Name = Convert.ToString(myReader["Name"]);
   objPerson.Age = Convert.ToInt32(myReader["Age"]);

   dbItems.Add(objPerson);
}

答案 2 :(得分:1)

什么列表?您是否有具有namefinalconc属性的班级设置?说你做,看起来像这样:

public class QueryResult
{
    public string Name { get; set; }
    //not sure what finalconc type would be, so here just using string
    public string FinalConc { get; set; }
}

然后你会做这样的事情:

var queryResults = new List<QueryResult>();
using(var myReader = myCommand.ExecuteReader())
{
    while(myReader.Read())
    {
        queryResults.Add(new QueryResult
            { 
                Name = myReader.GetString(myReader.GetOrdinal("name")), 
                FinalConc = myReader.GetString(myReader.GetOrdinal("finalconc"))
            });
    }
}