我有一個程序,我正在研究SQL DB中給定日期中的所有事件都會填充日曆。最近,我從MySQL切換到2012 MSSQL,現在我得到的錯誤"Conversion failed when converting date and/ or time from character string."
在日曆程序中去過去的日期
這裏是形成日期
'// Set Start and End Date
If numericMonth < 10 Then
doubleMonth = "0" & numericMonth 'If Month was September doubleMonth = 09
startDate = numericYear & "-" & doubleMonth & "-01" ' If date was June 1 2015 startdate would = 2015-06-01
Calendar1.Refresh()
Else
startDate = numericYear & "-" & numericMonth & "-01"
doubleMonth = numericMonth
End If
Dim endDate As String
If numericMonth < 10 Then
endDate = numericYear & "-0" & numericMonth & "-31"
Else
endDate = numericYear & "-" & numericMonth & "-31" ' If date was June 30 2015 enddate would = 2015-06-31
End If
If bypassMode = "0" Then
count = 0
dbQuery = "SELECT * FROM SOEVENTS WHERE DATE BETWEEN '" & startDate & "' AND '" & endDate & "' ORDER BY date ASC"
If SQL.HasConnection = True Then
SQL.RunQuery(dbQuery)
End If
最後的結局是格式YYYY-MM-DD的代碼。未來的所有月份都可以工作,但似乎過去的每3個月都沒有。
將一個字符串解析爲'datetime' _before_你將它傳遞給數據庫。因此使用'Date.Parse'或'Date.TryParse'。然後[使用sql-parameters](https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlparameter(v = vs.110).aspx)來提供這個參數。這樣你就避免了本地化和轉換問題,更重要的是,SQL注入。所以永遠不要使用字符串連接來構建你的sql查詢。 –
使用日期查詢數據庫。你正在變得非常容易出錯,而且你自己把所有東西都轉換成了一個字符串。 'Dim startDate As New DateTime(year,month,day)' –