'附近的语法不正确。字符串后面的未闭合引号

时间:2014-08-29 17:44:59

标签: sql vba

我正在使用查询从SQL数据库中提取数据,有时最后一个下拉列表我用来获取我正在寻找的记录有一个单引号,当它出现时我收到以下错误:语法附近不正确'S'。字符串后面的未闭合引号

这是我的代码:

Using objcommand As New SqlCommand("", G3SqlConnection)
        Dim DS01 As String = DDLDS01.SelectedItem.Text
        Dim State As String = DDLState.SelectedItem.Text
        Dim Council As String = DDLCouncil.SelectedItem.Text
        Dim Local As String = DDLLocal.SelectedItem.Text

        Dim objParam As SqlParameter
        Dim objDataReader As SqlDataReader
        Dim strSelect As String = "SELECT * " & _
            "FROM ConstitutionsDAT " & _
            "WHERE DS01 = '" & DS01 & "' AND STATE = '" & State & "' AND COUNCIL = '" & Council & "' AND LOCAL = '" & Local & "' AND JURISDICTION = '" & DDLJurisdiction.SelectedItem.Text & "' "

        strSelect.ToString.Replace("'", "''")
        objcommand.CommandType = CommandType.Text
        objcommand.CommandText = strSelect


        Try

            objDataReader = objcommand.ExecuteReader
            DDLJurisdiction.Items.Add("")
            While objDataReader.Read()
                If Not IsDBNull(objDataReader("SUBUNIT")) Then
                    txtSubUnit.Text = (objDataReader("SUBUNIT"))
                End If

                If Not IsDBNull(objDataReader("DS02")) Then
                    lblDS02.Text = (objDataReader("DS02"))
                End If
                If Not IsDBNull(objDataReader("LEGISLATIVE_DISTRICT")) Then
                    txtALD.Text = (objDataReader("LEGISLATIVE_DISTRICT"))
                End If
                If Not IsDBNull(objDataReader("REGION")) Then
                    txtRegion.Text = (objDataReader("REGION"))
                End If
                If DDLState.SelectedItem.Text <> "OTHER" Then
                    If Not IsDBNull(objDataReader("UNIT_CODE")) Then
                        txtUnitCode.Text = (objDataReader("UNIT_CODE"))
                    End If
                End If                   
            End While
            objDataReader.Close()
        Catch objError As Exception
            OutError.Text = "Error: " & objError.Message & objError.Source
            Exit Sub
        End Try
    End Using

并非所有记录都包含单引号,只有一些,所以如果存在单个引号,我需要一些可行的方法。 感谢。

2 个答案:

答案 0 :(得分:4)

你的问题就在这里:

strSelect.ToString.Replace("'", "''")

这正在改变你的WHERE子句,比如

WHERE DS01 = 'asdf' AND ...

要:

WHERE DS01 = ''asdf'' AND ...

您需要替换where子句中的各个值,而不是整个select语句。

你应该做的是改为使用parameterized query

更新:添加与aquinas相同的链接,因为它是一个很好的链接

答案 1 :(得分:2)

使用参数化查询,并且只有EVER使用参数化查询。请参阅:How do I create a parameterized SQL query? Why Should I?