我的数据库中有一个日期列。我有两个datetimepickers(过去和现在)三个单选按钮,零售商,子经销商和经销商。我想在我的数据网格中显示两个日期之间的所有记录。但首先我将设置两个日期并选择一个单选按钮,然后单击搜索按钮。我用radiobuttons解决了我的问题。我只是把" OR"在我的查询中,即使在两个日期之间获取日期的问题,它仍将仍然存在。 我没有使用datime,因为我在我的数据库中使用varchar作为date的数据类型。我不能把它改成日期时间,因为那是我老师给我的。
这是我的代码。非常感谢。
propertyGrid.Focus();
propertyGrid.SelectedProperty = propertyGrid.Properties[0];
答案 0 :(得分:0)
Since your date column is a varchar, you will have to use str_to_date. I would suggest you to use Parameters where the string in the query comes from the user, even if you aren't asked to, as this would save you from sql injections.
MySqlCommand cmd = new MySqlCommand("SELECT * FROM " + tablename + " WHERE STR_TO_DATE(`date`, '%Y/%m/%d') BETWEEN STR_TO_DATE(@pastvalue, '%Y/%m/%d') AND STR_TO_DATE(@presentvalue, '%Y/%m/%d') OR type LIKE '%" + type + "%'", con);
command.Parameters.AddWithValue("@pastvalue", past);
command.Parameters.AddWithValue("@presentvalue", present);
MySqlDataReader reader = cmd.ExecuteReader();
I am assuming that the dates are stored in the following format 2016/09/01. If the dates are in another fromat then change the formatting of str_to_date respectively.
Without Parameters the query would look like
MySqlCommand cmd = new MySqlCommand("SELECT * FROM " + tablename + " WHERE STR_TO_DATE(`date`, '%Y/%m/%d') BETWEEN STR_TO_DATE(past, '%Y/%m/%d') AND STR_TO_DATE(present, '%Y/%m/%d')" + "' OR type LIKE '%" + type + "%'", con);
答案 1 :(得分:0)
If you can't change the type of date column to Datetime
then your query will never work you have to manually implement your own date manipulation code assuming you have same date and time formats to compare in your query fetch all record regardless what date is then try following code
FilterData(ref rawData);
and the function definition is following
private void FilterData(ref List<Retailer> data)
{
for(int i = 0 ; i < data.Count ; i++)
{
Retailer d = data[i];
DateTime present = DateTime.parse(present);
DateTime past = DateTime.parse(past);
DateTime dt = DateTime.parse(d.Date);
if(!(dt >= past && dt < present))
data.RemoveAt(i); //remove record it is not between present and past
}
}