开发者

Unclosed quotation mark after the character string - What's wrong with this MSSQL query?

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Dim SQLData As New System.Data.SqlClient.SqlConnection("Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True")
        Dim cmdSelect As New System.Data.SqlClient.SqlCommand("SELECT * FROM Table1 WHERE Date =" & T开发者_如何学编程extBox1.Text & "'", SQLData)

        SQLData.Open()
        Dim dtrReader As System.Data.SqlClient.SqlDataReader = cmdSelect.ExecuteReader()
        While dtrReader.Read()
            For j As Integer = 1 To 31
                Dim s As String = "s" & j
                If dtrReader(s.ToString()).ToString() = "b" Then
                    Dim img As ImageButton = DirectCast(Panel1.FindControl(s.ToString()), ImageButton)
                    img.ImageUrl = "~/Images/booked.gif"

                    img.Enabled = False

                End If
            Next
        End While

        dtrReader.Close()
        SQLData.Close()
    End Sub

Error:

Unclosed quotation mark after the character string ''.


I think you should add another "'" before the date.

@ Line 3 after TextBox1.Text &

Also, I would highly recommend you to validate the date string from the textbox, here is an abstract example, not tested:

Dim input = TextBox1.Text
Dim dateVal As Date
Dim sqlDate As String
If Not Date.TryParse(input, dateVal) Then
  Throw New FormatException("Input date was invalid.")
Else
  Try
    sqlDate = New SqlDateTime(dateVal).ToSqlString
  Catch ex As Exception
    Throw New FormatException("Input date was invalid.")
  End Try
End If

Dim query = "SELECT * FROM Table1 WHERE Date = '" & sqlDate & "'"

If you want to compare only by years, months etc., it's very essential you should read this post as well.


I think it should be:

Dim cmdSelect As New System.Data.SqlClient.SqlCommand("SELECT * FROM Table1 WHERE Date ='" & TextBox1.Text & "'", SQLData)

I just added a ' after Date =.

But remember this is not a great way to build the query and makes the code prone to SQL Injection.


Try the following:

...
Dim cmdSelect As New System.Data.SqlClient.SqlCommand("SELECT * FROM Table1 WHERE Date = @Date", SQLData)
cmdSelect.Parameters.Add(New System.Data.SqlClient.SqlParameter("@Date", TextBox1.Text))
...
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜