我制作了一个程序,它使用OleDbDataReader
读取数据库中的数据,但问题是我有不同的表,这些代码工作正常,但我发现它有点“硬编码”或{{1}这是我的示例代码
recursive
我需要一次又一次地重复这一点,只是为了阅读另一张桌子上的内容(例如, 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();
}
然后"select* from Fruit
....)有什么办法让我不再重复这段代码一次又一次?
感谢:)
答案 0 :(得分:4)
您可以将该方法重构为以下内容:
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;
}
您的代码示例将是:
var milkItems = Load("Milk", "Product");
var classicItems = Load("Classics", "..."); //Enter the column here.
修改强>:
您可能想要更具体的内容(例如,存储List<SomeObject>
而不仅仅是List<string>
)。假设您有时想要返回Person
列表,并且还想阅读Building
列表。然后你可以写这样的东西(未编译和测试):
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;
}
你可以这样称呼:
Func<OleDbDataReader, Person> selector = x => new Person { Name = x["Person"].ToString() };
Load("People", selector);
答案 1 :(得分:3)
private void loadMilk(string TableName, string itemValue)
{
string SQLString = String.Format("select * from {0}",TableName);
cn.Open();
OleDbDataReader reader = null;
OleDbCommand cmd = new OleDbCommand(SQLString, cn);
reader = cmd.ExecuteReader();
while (reader.Read())
{
Milk.Add(reader[ItemValue].ToString());
}
cn.Close();
}
答案 2 :(得分:1)
不确定“Milk”是什么类型。 尝试:
private void loadObjectsFrom(string tableName, object obj, string column)
{
cn.Open();
OleDbDataReader reader = null;
OleDbCommand cmd = new OleDbCommand("select* from " + tableName, cn);
reader = cmd.ExecuteReader();
while (reader.Read())
{
obj.Add(reader[column].ToString());
}
cn.Close();
}
答案 3 :(得分:0)
只需将表名作为参数传递:
private void loadMilk(string tableName)
{
cn.Open();
OleDbDataReader reader = null;
OleDbCommand cmd = new OleDbCommand(string.Format("select* from {0}",tableName), cn);
reader = cmd.ExecuteReader();
while (reader.Read())
{
Milk.Add(reader["Product"].ToString());
}
cn.Close();
}