匹配数据库ms访问中的查询日期时间

时间:2014-01-28 04:06:12

标签: c# ms-access

嗨,我有像这样的数据库访问的日期时间格式

1/18/2014 4:14:52 PM (M/DD/YYYY h/mm/ss)

当我尝试选择以下代码的查询时

Global.dbCon.Open();
  string kalimatsql2 = "SELECT * FROM Quiz_Occurrences WHERE Occurred = " +dt2+ " 
                            ORDER BY ID";
  Global.reader = Global.riyeder(kalimatsql2);
  if (Global.reader.HasRows) {
     while (Global.reader.Read()) {
        int idku = Convert.ToInt32(Global.reader.GetValue(0));
        MessageBox.Show(idku.ToString());
     }
  }
  Global.dbCon.Close();

给出错误结果
查询表达式中的语法错误(缺少运算符)'发生= 1/12/2014 4:18:59 PM'

这是我的dt2 var

DateTime dt2 = (DateTime) myDataGridView.CurrentRow.Cells[3].Value;

我已经检查了很多次... dt与数据库中的datetime具有相同的格式 但它仍然给出错误结果....如何正确查询


修改

这是我的Global.riyeder

public static OleDbDataReader riyeder(string kalimatSql) {
    dbCmd.CommandText = kalimatSql;
    return dbCmd.ExecuteReader();            
}

2 个答案:

答案 0 :(得分:1)

您缺少属性发生的值的单引号。它应该是

 string kalimatsql2 = "SELECT * FROM Quiz_Occurrences WHERE Occurred = '" +dt2+ "' 
                            ORDER BY ID";

答案 1 :(得分:1)

试试这个

Global.dbCon.Open();
  string kalimatsql2 = "SELECT * FROM Quiz_Occurrences WHERE Format(DateOccurred, 'mm/dd/yyyy') = Format( '" + dt2+ "', 'mm/dd/yyyy') ORDER BY ID";
  Global.reader = Global.riyeder(kalimatsql2);
  if (Global.reader.HasRows) {
     while (Global.reader.Read()) {
        int idku = Convert.ToInt32(Global.reader.GetValue(0));
        MessageBox.Show(idku.ToString());
     }
  }
  Global.dbCon.Close();