在這裏,我是新來的c#。我有一個comboBox代碼,使用戶可以選擇月份和日期。當用戶點擊cmdSend按鈕,程序將檢索月份&日期格式組合框和調用dbConnect.Select類功能做選擇MySQL的聲明。如何根據組合框中的選定值從數據庫檢索數據?
private void cmdSend_Click(object sender, System.EventArgs e)
{
List<string>[] list;
list = dbConnect.Select(month_list.Text, year_list.Text);
printer_info.Rows.Clear();
for (int i = 0; i < list[0].Count; i++)
{
int number = printer_info.Rows.Add();
printer_info.Rows[number].Cells[0].Value = list[0][i];
printer_info.Rows[number].Cells[1].Value = list[1][i];
printer_info.Rows[number].Cells[2].Value = list[2][i];
printer_info.Rows[number].Cells[3].Value = list[3][i];
}
}
檢索數據庫類:
public List<string>[] Select(string month,string year)
{
string query = "SELECT * FROM page_counter where month ='" + month + "' AND year ='" + year + "' ;";
//Create a list to store the result
List<string>[] list = new List<string>[4];
list[0] = new List<string>();
list[1] = new List<string>();
list[2] = new List<string>();
list[3] = 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())
{
list[0].Add(dataReader["id"].ToString() + "");
list[1].Add(dataReader["month"].ToString() + "");
list[2].Add(dataReader["year"].ToString() + "");
list[3].Add(dataReader["page_count"].ToString() + "");
}
//close Data Reader
dataReader.Close();
//close Connection
this.CloseConnection();
//return list to be displayed
return list;
}
else
{
return list;
}
}
但是這個代碼不工作,有人可以告訴我嗎?
編輯:
string query = "SELECT * FROM page_counter where month = @month AND year = @year;";
//Open connection
if (this.OpenConnection() == true)
{
//Create Command
MySqlCommand cmd = new MySqlCommand(query, connection);
cmd.Parameters.AddWithValue("@month",month);
cmd.Parameters.AddWithValue("@year",year);
//Create a data reader and Execute the command
MySqlDataReader dataReader = cmd.ExecuteReader();
//Read the data and store them in the list
while (dataReader.Read())
{
list[0].Add(dataReader["id"].ToString() + "");
list[1].Add(dataReader["month"].ToString() + "");
list[2].Add(dataReader["year"].ToString() + "");
list[3].Add(dataReader["page_count"].ToString() + "");
}
//close Data Reader
dataReader.Close();
我已編輯的建議的代碼,但是我對AddWithValue一個錯誤,它說:不包含AddWithValue的定義,並沒有擴展方法AddWithValue,我已經添加了Data.MySqlClient引用但仍保持不變。請指教。
是asp.net或WinForm的? –
@ SaghirA.Khatri這是winform c#。 – Ren