【问题标题】:VB.NET Access Datetime Querying IssueVB.NET 访问日期时间查询问题
【发布时间】:2015-02-18 11:56:04
【问题描述】:

我在带有日期时间字段的 Access db 表中有一堆记录

例如记录(2/2/2015 3:34:21 PM,2/2/2015 8:29:13 AM)

问题是我需要运行一个查询,在该查询中我需要显示的所有记录都是在同一天发生的记录,无论时间如何。如何最好地构造这个查询?

我使用了“Select * from table where thetime = 2/2/2015”,但没有返回任何结果。我将日期格式切换为以年份开头,没有运气。

任何关于 Access 的 sql 查询语法的提示将不胜感激。谢谢。

【问题讨论】:

    标签: vb.net datetime ms-access


    【解决方案1】:

    Access 中的日期/时间值始终同时包含日期和时间部分,因此像 2015-02-02 这样的日期文字等价于 2015-02-02 00:00:00。如果您想要该日期的所有行,无论时间如何,您都需要使用 WHERE 子句,如

    ... WHERE thetime >= {that date} AND thetime < {the following day}
    

    在 VB.NET 中执行此操作的正确方法是使用如下参数化查询:

    Using cmd As New OleDbCommand()
        cmd.Connection = con  ' an open OleDbConnection
        cmd.CommandText =
                "SELECT * FROM thetable " &
                "WHERE thetime >= ? AND thetime < ?"
        Dim targetDate As New DateTime(2015, 2, 2)  ' example data
        cmd.Parameters.Add("?", OleDbType.DBTimeStamp).Value = targetDate
        cmd.Parameters.Add("?", OleDbType.DBTimeStamp).Value = targetDate.AddDays(1)
        Using rdr As OleDbDataReader = cmd.ExecuteReader
            Do While rdr.Read()
                Console.WriteLine(rdr("thetime"))
            Loop
        End Using
    End Using
    

    【讨论】:

      猜你喜欢
      • 2011-09-25
      • 1970-01-01
      • 2016-09-14
      • 2018-08-06
      • 1970-01-01
      • 2011-07-23
      • 1970-01-01
      • 2013-05-13
      相关资源
      最近更新 更多