icecub icecub - 5 months ago 8
MySQL Question

Need a little bit of help finishing a generic MySQL select method

General info

I'm busy writing my own MySQL database class inside C#. At the moment I'm trying to write a Select method that accepts a select query and returns a List with all the data. I'm still very new to C# so if my approach to this problem is wrong, please do not hesitate to tell me.

The problem

Right now my method expects 2 parameters. The query and the number of columns selected by the query. With that info I prepare my List and start filling it up. To do this I'm relying on the amount of columns with a foreach loop. However, I have no idea on how to get the correct column names
when adding to the List. Aside from that, I'm not sure if my approach is going to work. So I hope you guys would like to take a look at my method and help me out finishing it.

The method

public List<string>[] Select(string query, int items)
{
//Create a list to store the result
List<string>[] resultList = new List<string>[items];

for(int i = 0; i < items; i++)
{
resultList[i] = new List<string>();
}

//Open connection
if (this.OpenConnection() == true)
{
//Create Command
MySqlCommand cmd = new MySqlCommand(query, connection);
//Create a data reader and Execute the command
MySqlDataReader dataReader = cmd.ExecuteReader();

//Read the data and store them in the list
while (dataReader.Read())
{
for(int j = 0; j < items; j++)
{
resultList[j].Add(dataReader["columnName_here"] + "");
}
}

//close Data Reader
dataReader.Close();

//close Connection
this.CloseConnection();

//return list to be displayed
return resultList;
}
else
{
return resultList;
}
}

Answer

MySqlDataReader is derived from System.Data.Common.DbDataReader, so you can use this code to get the columns:

for (int c = 0; c < dataReader.FieldCount; c++)
{
    string name = dataReader.GetName(c);
    Type type = dataReader.GetFieldType(c);
}
Comments