无法使用SQL Query来使用SafeSqlLiteral函数

时间:2016-05-24 13:04:43

标签: sql vb.net

我在网上找到了一个SafeSqlLiteral函数。它是防止SQL注入攻击的功能。我想在我的SQL查询中使用此函数,如下所示:

Dim com As String = "SELECT * FROM Person WHERE " &  
                     SafeSqlLiteral(SearchCriteria, 2)

SearchCriteria是用户输入。我希望用户能够输入:strState LIKE' M%'并显示与缅因州相匹配的所有记录。感觉这会起作用。 (SELECT * FROM Person WHERE strState LIKE' M%')

我收到了一大堆错误(可能在这里发布的内容太多了,但如果需要可以发布),而且我很难弄清楚如何使我的查询工作SafeSqlLiteral函数。

这是SafeSqlLiteral函数:

Public Function SafeSqlLiteral(theValue As System.Object,
                               theLevel As System.Object) As String

        Dim strValue As String = DirectCast(theValue, String)
        Dim intLevel As Integer = CInt(theLevel)

        If strValue IsNot Nothing Then
            If intLevel > 0 Then
                strValue = strValue.Replace("'", "''")
                strValue = strValue.Replace("--", "")
                strValue = strValue.Replace("[", "[[]")
                strValue = strValue.Replace("%", "[%]")
            End If
            If intLevel > 1 Then
                Dim myArray As String() = New String() {"xp_ ", "update ", "insert ", "select ", "drop ", "alter ",
        "create ", "rename ", "delete ", "replace "}
                Dim i As Integer = 0
                Dim i2 As Integer = 0
                Dim intLenghtLeft As Integer = 0
                For i = 0 To myArray.Length - 1
                    Dim strWord As String = myArray(i)
                    Dim rx As New Regex(strWord, RegexOptions.Compiled Or RegexOptions.IgnoreCase)
                    Dim matches As MatchCollection = rx.Matches(strValue)
                    i2 = 0
                    For Each match As Match In matches
                        Dim groups As GroupCollection = match.Groups
                        intLenghtLeft = groups(0).Index + myArray(i).Length + i2
                        strValue = strValue.Substring(0, intLenghtLeft - 1) + " " + strValue.Substring(strValue.Length - (strValue.Length - intLenghtLeft), strValue.Length - intLenghtLeft)
                        i2 += 5
                    Next
                Next
            End If
            Return strValue
        Else
            Return strValue
        End If

    End Function

提前感谢任何帮助我解决此问题的人!非常感谢!

0 个答案:

没有答案