我在我的数据库中有一个日期列。我有两个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