Question

Just a quick questions, since most blogs and tutorials I found are about the very basic elements of MySQL and C#.

I am using the MySQL ADO Connector.

I have everything setup and I can retrieve data from the table. But I want to create a method that simplifies things for me. So I can set a query string (either in the method or the object) and call a function and it would return some sort of a data object.

// For each row
while(reader.Read())
{
    // For each column
    for(int i = 0; i < reader.FieldCount; i++)
    {
        Console.Write(reader.GetName(i).ToString());
        Console.Write(reader.GetValue(i).ToString() + ",");
    }
    Console.Write("\n");
}

This is what I have now. I could probably just return the reader. But that would require a for loop in a while loop every time I would want to loop through some data.

Wondering if there is a better data object I could fill and return? I would also love links to reading material on this.

BTW I am learning C# so there might be things I'm not 100% clear on.

Was it helpful?

Solution

You should not pass the data reader around. You have to keep the database connection open as long as you are reading from the data reader, so you should read the data that you want into some collection so that you can close the database connection as early as possible.

You can read the data into a DataSet or a DataTable, or you can create classes for your objects and populate directly. Example:

List<SomeCustomObject> data = new List<SomeCustomObject>();
while(reader.Read()) {
   int id = reader.GetInt32(0);
   string name = reader.GetString(1);
   data.Add(new SomeCustomObject(id, name);
}

OTHER TIPS

Why not just use the ADO.NET provider for MySql, and return a standard ADO.NET DataSet?

This has the advantage of keeping your code that deals with the data portable to other DB backends.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top