将结果集从OleDbDataReader到列表 [英] converting resultset from OleDbDataReader into list

查看:153
本文介绍了将结果集从OleDbDataReader到列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Consider a Winforms app connecting to a SQL Server 2008 database and running a SQL SELECT statement:

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);

如何阅读查询的结果变成一个列表?

How can you read the results of the query into a list?

推荐答案

假设你定义一个类,它是像

Assume you have defined a class that is something like

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

您会遍历查询的结果加载列表。

You would iterate through the results of your query to load a list.

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

如果你只需要在给定的领域之一,你可以放弃类的定义,只是有一个名单,其中,T&GT; ,其中 T 是无论你怎样想拥抱的类型。

If you just need one of the given fields, you can forego the class definition and simply have a List<T>, where T is the type of whatever field you want to hold.

这篇关于将结果集从OleDbDataReader到列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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