VB.NET Access Datetime Querying Issue

不想你离开。 提交于 2019-12-24 14:57:18

问题


I have a bunch of records in an Access db table with a datetime fields

e.g of records (2/2/2015 3:34:21 PM,2/2/2015 8:29:13 AM )

Problem is I need to run a query where I need all records for displayed to be ones that occurred on the same day regardless of the time. How to best structure this query?

I used 'Select * from table where thetime = 2/2/2015' and there was no result returned. I switched the date format to start with the year, no luck.

Any tips as to sql query syntax for Access will be appreciated. Thanks.


回答1:


Date/Time values in Access always have both a date and time component, so a date literal like 2015-02-02 is equivalent to 2015-02-02 00:00:00. If you want all rows for that date, regardless of the time, you need to use a WHERE clause like

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

The proper way to do that in VB.NET is to use a parameterized query like this:

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


来源:https://stackoverflow.com/questions/28583059/vb-net-access-datetime-querying-issue

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!