1
一般信息
我忙於在C#中編寫自己的MySQL數據庫類。此刻,我正在嘗試編寫一個Select方法,它接受一個select查詢並返回一個包含所有數據的List。我對C#仍然很陌生,所以如果我對這個問題的解決方法是錯誤的,請不要猶豫,告訴我。需要一點幫助完成通用的MySQL選擇方法
問題
現在我的方法需要2個參數。查詢和查詢選擇的列數。有了這些信息,我準備好我的清單並開始填寫。要做到這一點,我依靠foreach循環的列數量。但是,我不知道在添加到列表時如何獲得正確的列名稱 。除此之外,我不確定我的方法是否會起作用。所以我希望你們想看看我的方法,並幫助我完成它。
方法
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;
}
}
感謝。我自己在發佈它的同時找到了解決方案,哈哈:)太棒了! – icecub