我在MS Access / VB.net中有以下SQL查询:
Dim sql = "SELECT [Product Name], [Customer Name], [Group Associated], [Customer Address], [Product Price], [Current Stock], [Date Ordered], [Volume Purchased] FROM (torder INNER JOIN tproducts ON tproducts.Product_ID = torder.Product_ID) INNER JOIN tcustomer ON torder.Customer_ID = tcustomer.Customer_ID WHERE torder.[Date Ordered] Between #" & StartOfTimePeriod & "# And #" & Today & "#;"
conn.Open()
Dim dataAdapter As New OleDbDataAdapter(sql, conn)
Dim ds As New DataSet()
dataAdapter.Fill(ds, "torder")
conn.Close()
DataGridView.DataSource = ds
DataGridView.DataMember = "torder"
运行查询时,它不会显示应该完整的数据集。相反,结果几乎是随机的。可能有什么不对?
答案 0 :(得分:2)
请勿对日期和时间值进行字符串化。使用参数化查询。
Dim sql = "SELECT [Product Name], [Customer Name], [Group Associated], " & _
"[Customer Address], [Product Price], [Current Stock], [Date Ordered], " & _
"[Volume Purchased] " & _
"FROM (torder INNER JOIN tproducts ON tproducts.Product_ID = torder.Product_ID) " & _
"INNER JOIN tcustomer ON torder.Customer_ID = tcustomer.Customer_ID " & _
"WHERE torder.[Date Ordered] >= ? And torder.[Date Ordered] <= ?"
Dim dataAdapter As New OleDbDataAdapter(sql, conn)
Dim p1 = new OleDbParameter() With
{
.ParameterName = "@p1",
.OleDbType = OleDbType.Date,
.Value = StartOfTimePeriod
}
Dim p1 = new OleDbParameter() With
{
.ParameterName = "@p2",
.OleDbType = OleDbType.Date,
.Value = DateTime.Today.AddMinutes(1339)
}
dataAdapter.SelectCommand.Parameters.Add(p1)
dataAdapter.SelectCommand.Parameters.Add(p2)
....
通过这种方式,对DateTime值的正确解释是与实际DateTime值一起传递给数据库引擎的作业(我假设StartOfTimePeriod是DateTime变量)。 相反,如果将这些值转换为字符串,则转换将遵循您的语言环境的规则,这些规则可能会生成与数据库引擎的预期格式不兼容的字符串(例如,月份和日期值的位置反转)