我在日期时间格式转换中遇到问题。在我的数据库表中,我有一列jour
的格式如下:
01/02/2014 00:00:00
即DD/MM/YYYY 00:00:00
。当我这样做时:
Dim date1 As String = Session("date1")
Dim date2 As String = Session("date2")
Dim datefirst As DateTime
Dim dateSecond As DateTime
Try
datefirst = DateTime.Parse(date1)
dateSecond = DateTime.Parse(date2)
Catch ex As Exception
End Try
Dim report As ReportDocument = New ReportDocument()
Dim reportPath As String = Server.MapPath("Reports\Prix.rpt")
Dim ds As DataSet
Dim cnn As SqlConnection
Dim connectionString As String = "Data Source=HP-PC\SQLEXPRESS;Initial Catalog=ReportingFormation;Integrated Security=True;Pooling=False"
Dim sql As String = ""
Dim dscmd As SqlDataAdapter
cnn = New SqlConnection(connectionString)
cnn.Open()
sql = "SELECT * FROM PrixProduit where ( Jour >= '" + datefirst + "'and Jour <='" + dateSecond + "')"
dscmd = New SqlDataAdapter(sql, cnn)
ds = New DataSet()
dscmd.Fill(ds, "PrixProduit")
使用这些值:date1 = 30/01/2014
date2 = 06/02/2014
datefirst = #1/30/2014#
dateSecond =#2/6/2014#
所以我得到了这个错误
The conversion of a char data type to a datetime data type resulted in an out-of-range datetime value.
在这行代码中:
dscmd.Fill(ds, "PrixProduit")
所以我需要知道
对于这种情况,您有两个选择,第一个是更改date
应用程序以匹配date
数据库。其次是在期间包含风格convert
。下面是例子试图convert
varchar
以date
场。首先select
会失败。但是第二个将起作用,因为我指定了style
我期望的字符串。
DECLARE @datechar VARCHAR(12) = '16/03/2014'
SELECT CONVERT(DATE, @datechar)
SELECT CONVERT(DATE, @datechar, 103)
您需要将SQL代码修改为以下内容
sql = "SELECT * FROM PrixProduit where ( Jour >= Convert(date,'" + datefirst + "',103 ) and Jour <= Convert(date,'" + dateSecond + "',103))"
就像已经提到的人一样,您应该避免使应用易于进行sql注入的字符串串联。因此,为此修改代码。
sql = "SELECT * FROM PrixProduit where Jour >= Convert(date,@datefirst,103 ) and Jour <= Convert(date,@datesecond,103)"
之后,只需将参数添加到您的命令中即可。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句