views:

49

answers:

2

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.

+2  A: 

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.

Reed Copsey
I am using that, could you perhaps elaborate?
Ólafur Waage
I found this forum post regarding DataSet and the DataAdapter: http://forums.mysql.com/read.php?38,50575,50575
Ólafur Waage
That post shows the process. Look at the line "myDA.Fill(myDS, "dsUno");" - it's filling the ADO.NET DataSet from the results of a command. You can then just use this, as it has all of the information required to work with the data, and you can close the reader.
Reed Copsey
+1  A: 

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);
}
Guffa
Great answer :) Could you link to or show an example for the dataset version. Since I'm not familiar with it.
Ólafur Waage
The easiest is to create a DataTable object and use the Load method to read the data from the data reader into it.
Guffa
Thanks. It works perfectly. :)
Ólafur Waage