考虑连接到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);
如何将查询结果读入列表?
答案 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)
什么列表?您是否有具有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"))
});
}
}