converting resultset from OleDbDataReader into list

二次信任 提交于 2019-12-02 19:02:41

问题


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?


回答1:


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

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.




回答2:


You can try something as (adapt it for your convenience):

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



回答3:


List of what? Do you have a class setup that has properties for name and finalconc? Saying you do, and it looks like this:

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

Then you would do something like this:

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


来源:https://stackoverflow.com/questions/4089628/converting-resultset-from-oledbdatareader-into-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!