【发布时间】:2016-01-19 04:13:25
【问题描述】:
我正在开发一个程序,其中 SQL DB 中给定日期的所有事件都会填充日历。我最近从 MYSQL 切换到 MSSQL 2012,现在收到错误 "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在你将它传递给数据库。因此使用Date.Parse或Date.TryParse。然后use sql-parameters提供这个参数。这样你就可以避免本地化和转换问题,更重要的是,sql-injection。所以永远不要使用字符串连接来构建你的 sql 查询。 -
使用日期查询数据库。您自己将所有内容都转换为字符串时非常容易出错和复杂。
Dim startDate As New DateTime(year, month, day)
标签: mysql sql-server vb.net