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#).

E.g. 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:

conn.Open();
string getNameQuery = "SELECT * FROM myTable";
MySqlCommand getName = new MySqlCommand(getNameQuery, conn);
dataReader = getName.ExecuteReader();
while(dataReader.Read())
{
    dataReader.getString("name");
}
conn.Close();

Answer

Create a List and add the values to it.

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. There is no need to fetch other columns.

Leave a Reply

Your email address will not be published. Required fields are marked *