0

考虑一个连接到 SQL Server 2008 数据库并运行 SQLSELECT语句的 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);

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

4

3 回答 3

3

假设您已经定义了一个类似于

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是您想要保存的任何字段的类型。

于 2010-11-03T17:16:58.473 回答
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);
}
于 2010-11-03T17:17:03.913 回答
1

什么清单?您是否有具有 和 属性的类name设置finalconc?说你这样做,它看起来像这样:

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"))
            });
    }
}
于 2010-11-03T17:19:56.413 回答