我如何使用参数来避免sql攻击

时间:2015-06-23 09:38:32

标签: sql vb.net

我有一个没有在SQL查询中使用任何参数的项目。 是否有任何解决方案,以便我不必更改函数并验证查询字符串本身的参数?

Query = "select * from tbl_Users where userName='"& textbox1.text &"' and password='"& textbox2.text &"' "
ds = obj.ExecuteQueryReturnDS(Query)

传递查询的函数:

Public Function ExecuteQueryReturnDS(ByVal stQuery As String) As DataSet
        Try
            Dim ds As New DataSet
            Using sqlCon As New SqlConnection(connStr)
                Dim sqlCmd As New SqlCommand(stQuery, sqlCon)
                Dim sqlAda As New SqlDataAdapter(sqlCmd)
                sqlCmd.CommandType = CommandType.Text
                sqlAda.Fill(ds)
            End Using
            Return ds
        Catch ex As Exception

        End Try
    End Function

我尝试将参数传递给函数,但该函数也用于其他查询,因此我无法在函数内定义参数。

是否有任何解决方法

2 个答案:

答案 0 :(得分:3)

我认为唯一的解决方案是创建一个新功能并逐渐迁移到它。

Public Function ExecuteQueryReturnDS(ByVal cmdQuery As SqlCommand) As DataSet

    Try
        Dim ds As New DataSet
        Using sqlCon As New SqlConnection(connStr)
            cmdQuery.Connection = sqlCon
            Dim sqlAda As New SqlDataAdapter(cmdQuery)
            sqlAda.Fill(ds)
        End Using
        Return ds
    Catch ex As Exception
    End Try

End Function

cmdQuery旨在成为您已添加所需参数的SqlCommand

答案 1 :(得分:1)

作为切换到完整参数化应用程序之前的中间步骤,您可以更改实际方法以便能够接收可选参数。 此可选参数将是您在调用此查询时定义的SqlParameter数组

Public Function ExecuteQueryReturnDS(ByVal stQuery As String, Optional ByVal prms As SqlParameter() = Nothing) As DataSet
   Try
       Dim ds As New DataSet
       Using sqlCon As New SqlConnection(connStr)
           Dim sqlCmd As New SqlCommand(stQuery, sqlCon)
           if Not prms Is Nothing Then
               sqlCmd.Parameters.AddRange(prms)
           End if
           Dim sqlAda As New SqlDataAdapter(sqlCmd)
           sqlCmd.CommandType = CommandType.Text
           sqlAda.Fill(ds)
       End Using
       Return ds
   Catch ex As Exception

   End Try
End Function