似乎每個人都恨DateTime
值。更改格式
在我的項目,我有一個SQL SELECT
查詢在數據庫中找到相匹配的結果的參數值。
我的代碼是:
Dim where As String = "WHERE [Supp_Code] = @scode " & _
"AND [DateFrom] = @datfrom " & _
"AND [DateTo] = @datto " & _
"AND [Comm_Code] = @ccode " & _
"AND [Customer_Code] = @custcode "
Dim sql As String = "SELECT [Comm_Code], [AqYear] FROM [Acquisition Commission] "
sql &= where & " ORDER BY [AqYear] ASC"
Dim cmd As New OleDb.OleDbCommand(sql, con)
cmd.Parameters.AddWithValue("@scode", cmbSupp.Text.Trim)
cmd.Parameters.AddWithValue("@datfrom", datFrom.Value)
cmd.Parameters.AddWithValue("@datto", datTo.Value)
cmd.Parameters.AddWithValue("@ccode", txtCommCode.Text)
cmd.Parameters.AddWithValue("@custcode", cmbCustomerCode.Text)
Dim daYear As New OleDb.OleDbDataAdapter(cmd)
Dim dsYear As New DataSet
daYear.Fill(dsYear)
代碼本身沒有問題。問題在於DataSet
只有0行,因爲datFrom.Value
(它是DateTimePicker
控件)的DateTime
格式爲'MM/dd/yyyy',但在數據庫中它存儲爲'dd/MM/yyyy'。
什麼是使用它作爲一個參數之前轉換其正確的數據庫格式的最簡單的方法?
編輯
使用下面的意見/答案,我已經適應我的代碼如下:
Dim test As DateTime
Dim test2 As DateTime
test = ugDates.ActiveRow.Cells("DateFrom").Value
test = ugDates.ActiveRow.Cells("DateTo").Value
Try
Dim where As String = "WHERE [Supp_Code] = @scode " & _
"AND [DateFrom] = @datfrom " & _
"AND [DateTo] = @datto " & _
"AND [Comm_Code] = @ccode " & _
"AND [Customer_Code] = @custcode "
Dim sql As String = "SELECT DISTINCT [Comm_Code], [AqYear] FROM [Acquisition Commission] "
sql &= where & " ORDER BY [AqYear] ASC"
Dim cmd As New OleDb.OleDbCommand(sql, con)
cmd.Parameters.Add("@scode", OleDbType.VarChar).Value = cmbSupp.Text
cmd.Parameters.Add(New OleDbParameter("@datfrom", OleDbType.Date).Value = test)
cmd.Parameters.Add(New OleDbParameter("@datto", OleDbType.Date).Value = test2)
cmd.Parameters.Add("@ccode", OleDbType.VarChar).Value = txtCommCode.Text
cmd.Parameters.Add("@custcode", OleDbType.VarChar).Value = cmbCustomerCode.Text
但是,它給我的第二個參數以下錯誤:
的OleDbParameterCollection只接受非空OleDbParameter類型的對象,而不是布爾對象。
將datFrom.ToString(「dd/MM/yyyy」)足夠嗎? –
請參閱[我們是否可以停止使用AddWithValue()](http://blogs.msmvps.com/jcoehoorn/blog/2014/05/12/can-we-stop-using-addwithvalue-already/) –
我希望你的日期列使用日期列類型(而不是varchar/string)? –