问题
I have a very simple problem. I have a couple of datepicker controls on my VB.NET form and users select "startDate" and "endDate", and all rows from the related table are displayed which have an orderDate
between the user's selected start and end dates.
The following is the relevant code:
Private Sub generate_report_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles generate_report.Click
Try
Dim con As New OleDb.OleDbConnection
con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\KHMSDB.accdb"
con.Open()
Dim sql As String
Dim selected As String = ""
Dim ds As DataSet = New DataSet
Dim adapter As New OleDb.OleDbDataAdapter
sql = "SELECT OrderDate AS `Order Date and Time`, Items AS `Ordered Items` FROM Orders WHERE Format(Orders.OrderDate,'mm/dd/yyyy') >= #" + startDate.Value.Date + "# AND Format(Orders.OrderDate,'mm/dd/yyyy') <= #" + endDate.Value.Date + "#"
adapter.SelectCommand = New OleDb.OleDbCommand(sql, con)
adapter.Fill(ds)
gridReport.DataSource = ds.Tables(0)
Catch ex As Exception
MsgBox("Operation failed. " + ex.ToString)
End Try
If I save a new row in the database under today's date, and I leave the "start" and "end" dates both as the default date (i.e. today's date), it doesn't show the new row I just saved. The new row entered today only shows up if I move the "start date" up to the 30th of November. Then I add a new row with date 12th December. Again, it won't show up when I select the end date to be >= 12 December, it'll only show up when I move the start date up to 1st December. I decided to enter a row dated 21st November, and running the query with start and end date both on 21st November shows up that row. I then entered a new row in January 8th.. and now any combination of moving up startDate and or moving down endDate just doesn't display the January order. What's going on?? I've actually already tried this code out before in November and it worked perfectly fine!
回答1:
What could be the issue with this is the string format. I'm not sure if Access will convert the string to a Date and then compare or convert the Date to a string and then compare. You can try this:
Format(Orders.OrderDate,'mm/dd/yyyy') >= Format(#" + startDate.Value.Date + "#,'mm/dd/yyyy')
Or you could always just use the date directly,
OrderDate >= #" + startDate.Value.Date + "#"
Edit:, to do my due diligence, you really should be doing the query like this
OrderDate >= @StartDate
Then add this code
adapter.Parameters.Add("@StartDate", startDate.Value.Date);
Using parameters is important for robust code and to avoid the dreaded SQL injection attack.
来源:https://stackoverflow.com/questions/13769768/selecting-rows-from-access-database-by-date-search-criteria-in-vb-net-form