2

我有以下 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。

我错过了什么?

4

1 回答 1

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
于 2013-08-23T14:38:04.817 回答