[英]Save all records from one table column in an array
I want to store all records from a MySQL table column in an array (C#).我想将 MySQL 表列中的所有记录存储在数组(C#)中。
Eg if there is the column "name" in a table:例如,如果表中有列“名称”:
name姓名 | other column其他栏目 | ... ... |
---|---|---|
Peter彼得 | ||
Marc马克 | ||
Henry亨利 |
... I want to store these names as elements in an array/list programmatically. ...我想以编程方式将这些名称存储为数组/列表中的元素。 The goal is to be able to access each element (in this case name) itself and going on with that.目标是能够访问每个元素(在本例中为名称)本身并继续进行。
Using a MySqlDataReader didn't work out that good, because it only returned me the last record in the column:使用 MySqlDataReader 并没有那么好,因为它只返回了我列中的最后一条记录:
conn.Open();
string getNameQuery = "SELECT * FROM myTable";
MySqlCommand getName = new MySqlCommand(getNameQuery, conn);
dataReader = getName.ExecuteReader();
while(dataReader.Read())
{
dataReader.getString("name");
}
conn.Close();
Create a List
and add the values to it.创建一个List
并将值添加到其中。
List<string> ls = new List<string>();
while(dataReader.Read())
{
ls.Add(dataReader.GetString("name"));
}
Also, as I suggested, if you need only name
column then write the query SELECT name FROM myTable
.另外,正如我所建议的,如果您只需要name
列,请编写查询SELECT name FROM myTable
。 There is no need to fetch other columns.无需获取其他列。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.