2014-12-08 54 views
0

我在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" 

當查詢時,它會不顯示完整的數據集,它應該。相反,結果幾乎是隨機的。什麼可能是錯的?

http://prntscr.com/5eh4ge

http://prntscr.com/5eh4ai

+0

你在期待什麼?在msaccess中運行此查詢並使用應用程序運行時,您獲得了多少條記錄? – DevelopmentIsMyPassion 2014-12-08 09:21:43

+0

數據庫表定義中的[Date Ordered]是什麼類型? – Steve 2014-12-08 09:22:30

+0

[Date Ordered]是日期/時間 – Michael 2014-12-08 09:27:11

回答

2

不要stringize您的日期和時間值。使用參數化查詢。

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值的正確解釋與實際日期時間值傳遞給數據庫引擎一起工作(我假設StartOfTimePeriod是一個DateTime變量)。 相反,如果您將這些值轉換爲字符串,則轉換遵循您的語言環境規則,該規則可能會產生與數據庫引擎的預期格式不兼容的字符串(例如,月份和天數值的位置反轉)

相關問題