我有以下vb.net代码
Protected Sub submit_date_Click(sender As Object, e As System.EventArgs) Handles submit_date.Click
Using conn As New SqlConnection(ConfigurationManager.ConnectionStrings("GasNominationsConnectionString").ConnectionString)
conn.Open()
Using cmd As SqlCommand = conn.CreateCommand
cmd.CommandText = "select * from MorningReport where readdate = " & "'" & datedisplay.text & "'"
Dim sqlrd As SqlDataReader = cmd.ExecuteReader()
If sqlrd.HasRows Then sqlrd.Read()
Me.Label6.Text = sqlrd.Item("NteesHR")
End Using
End Using
End Sub
我遇到的问题是它没有读取任何数据。 datedisplay.text
是使用ajax日历扩展程序填充的文本框,当我调试数据时,我可以看到它为此示例获取了正确的日期22/08/2013
。然后我得到错误
没有数据时无效尝试读取。
我遇到的问题是,如果我将SQL语句复制到SQL Server Management Studio并对表运行它可以正常工作,我得到了我想要的结果。
SQL是
select * from MorningReport where readdate = '22/08/2013'
sql表中日期的格式为2013-08-22,类型为date。
我错过了什么?
答案 0 :(得分:2)
使用marc_s建议我使用参数化查询。请看下面。干杯
Protected Sub submit_date_Click(sender As Object, e As System.EventArgs) Handles submit_date.Click
Using conn As New SqlConnection(ConfigurationManager.ConnectionStrings("GasNominationsConnectionString").ConnectionString)
conn.Open()
Using cmd As SqlCommand = conn.CreateCommand
cmd.CommandType = CommandType.StoredProcedure
cmd.CommandText = "getMorningReportData"
cmd.Parameters.Add("datedisplay", SqlDbType.Date).Value = DateDisplay.Text
Dim sqlrd As SqlDataReader = cmd.ExecuteReader()
If sqlrd.HasRows Then
sqlrd.Read()
Me.Label6.Text = sqlrd.Item("NteesHR")
End If
End Using
End Using
End Sub