我在我的數據庫中有一個日期列。我有兩個datetimepickers(過去和現在)三個單選按鈕,稱爲零售商,分銷商和經銷商。我想在我的數據網格中顯示兩個日期之間的所有記錄。但首先我會設置兩個日期並選擇一個單選按鈕並單擊搜索按鈕。我用單選按鈕解決了我的問題。我只是把「OR」放在我的查詢中,這樣即使在兩個日期之間取得日期的問題也不會改變。 我沒有使用datime,因爲我在數據庫中使用了varchar作爲date的數據類型。我不能將它改爲datetime,因爲那是我老師給我的。從兩個日期之間的數據庫獲取所有記錄C#
這是我的代碼。十分感謝。
public static List<Retailer> GetDataByType(string type, string past, string present)
{
List<Retailer> data = new List<Retailer>();
MySqlConnection con = DBConnection.ConnectDatabase();
try
{ // AND
MySqlCommand cmd = new MySqlCommand("SELECT * FROM " + tablename + " WHERE date BETWEEN '" + past + "' AND '" + present + "'" + "' OR type LIKE '%" + type + "%'", con);
MySqlDataReader reader = cmd.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
Retailer rawData = new Retailer();
rawData.Date = reader.GetString(0);
rawData.Walletid = reader.GetString(1);
rawData.Fname = reader.GetString(2);
rawData.Lname = reader.GetString(3);
rawData.Birthdate = reader.GetString(4);
rawData.Address = reader.GetString(5);
rawData.Province = reader.GetString(6);
rawData.City = reader.GetString(7);
rawData.Balance = reader.GetDouble(8);
rawData.Frozen = reader.GetDouble(9);
rawData.Sponsor_id = reader.GetString(10);
rawData.Share = reader.GetDecimal(11);
rawData.Email = reader.GetString(12);
rawData.Password = reader.GetString(13);
rawData.Type = reader.GetInt32(14);
data.Add(rawData);
MessageBox.Show(rawData.Date);
}
}
reader.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
con.Close();
}
return data;
}
}
將字符串日期轉換爲日期:http://stackoverflow.com/questions/5201383/how-to-convert-a-string-to-date-in-mysql – Jens
「過去」的格式和「禮物」是這裏的關鍵。你需要讓它們處於默認的MySQL格式。但是,最佳解決方案是使用參數並將類型指定爲DateTime。 – user3185569
可能的重複:http://stackoverflow.com/questions/14952518/mysql-date-time-format-using-c-sharp – user3185569