将结果集从OleDbDataReader到列表结果、列表、OleDbDataReader

由网友(佰仙)分享简介:考虑WinForms应用程序连接到SQL Server 2008数据库和运行SQL SELECT 语句:Consider a Winforms app connecting to a SQL Server 2008 database and running a SQL SELECT statement:strin...

考虑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.

阅读全文

相关推荐

最新文章