I made a program, that reads data in the database I use the OleDbDataReader
but the problem is I have different tables, this codes works perfectly but I found it a little bit "hardcoded" or recursive
here is my sample code
private void loadMilk()
{
cn.Open();
OleDbDataReader reader = null;
OleDbCommand cmd = new OleDbCommand("select* from Milk", cn);
reader = cmd.ExecuteReader();
while (reader.Read())
{
Milk.Add(reader["Product"].ToString());
}
cn.Close();
}
I need to repeat this again and again just to read what's on the other table (e.g., "select* from Fruit
then "select* from Classics
....) Is there any way so that I will not repeat this code again and again?
thanks.:)
You can refactor that method into something like this:
private IList<string> Load(string tableName, string columnName)
{
var result = new List<string>();
cn.Open();
OleDbDataReader reader = null;
OleDbCommand cmd = new OleDbCommand(string.Format("select* from {0}", tableName), cn);
reader = cmd.ExecuteReader();
while (reader.Read())
{
result.Add(reader[columnName].ToString());
}
cn.Close();
return result;
}
Your code sample will be:
var milkItems = Load("Milk", "Product");
var classicItems = Load("Classics", "..."); //Enter the column here.
Edit:
You might want something a little more specific (eg. storing a List<SomeObject>
instead of just List<string>
). Let's suppose you sometimes you want to return a list of Person
, and also you want to read a list of Building
. Then you can write something like this (not compiled & tested):
private IList<T> Load<T>(string tableName, Func<OleDbDataReader, T> selector)
{
IList<T> result = new List<T>();
cn.Open();
OleDbDataReader reader = null;
OleDbCommand cmd = new OleDbCommand(string.Format("select* from {0}", tableName), cn);
reader = cmd.ExecuteReader();
while (reader.Read())
{
result.Add(selector(reader));
}
cn.Close();
return result;
}
and you can call it like:
Func<OleDbDataReader, Person> selector = x => new Person { Name = x["Person"].ToString() };
Load("People", selector);