防止SQL注入并使用SqlDataAdapter

时间:2017-01-24 20:40:27

标签: vb.net datagridview parameters sqlcommand sqldataadapter

所以我可以在VB.Net中运行一个应用程序,下面的代码是:

Private Sub LoadAttachments()
        tablegrid = New DataTable
        myConn = New SqlConnection("Server=CEDASDSOBSQL02\dev; Database=Insurance; Integrated Security=true")
        myConn.Open()
        myCmd = myConn.CreateCommand
        Dim query As String = "SELECT DocType, docyear, CASE WHEN docmonth IS NULL THEN NULL " & _
                  "WHEN docmonth = '0' THEN '- All Months -' WHEN docmonth >= 1 AND docmonth <= 12 " & _
                  "THEN DATENAME(month, DATEADD(month, docmonth, -1)) END DocMonth, DID from dbo.Document where XALASKAID = '" & LicenseNumber & "' and DOCTYPE like '%Report%'"
        da = New SqlDataAdapter(query, myConn)
        myCmd = New SqlCommand(query, myConn)
        myCmd.CommandType = CommandType.Text
        da = New SqlDataAdapter(myCmd)
        da.Fill(tablegrid)
        DataGridView3.DataSource = tablegrid
        Label4.Text = "Found " & DataGridView3.Rows.Count & " images"
    End Sub

所以这段代码是一个SQL注入XALASKAID = '" & LicenseNumber & "',它位于查询中。我不需要使用'" & LicenseNumber & "',而是需要将其更改为:@LicNum然后添加myCmd.Parameters.Add("@LicID", SqlDbType.Int) myCmd.Parameters("@LicID").Value = LicenseNumber

我使用参数获取LicenseNumber的所有内容都为null或为空。我在代码中需要一些助手,我想我正在重复使用太多的代码。如果可以简化一点,谢谢。

PS:我的所有声明都是全球性的。

1 个答案:

答案 0 :(得分:0)

我的原始代码中有不匹配的定义,我做了一些删除和更改。

Private Sub LoadAttachments()
        attachmentsTable = New DataTable

        Dim mAdapter As New SqlDataAdapter
        If LicenseNumber IsNot Nothing Then
            If Not String.IsNullOrEmpty(InsCommonLib.Settings.MSSqlConStr) Then
                Dim query As String = "SELECT DocType, docyear, CASE WHEN docmonth IS NULL THEN NULL " & _
                          "WHEN docmonth = '0' THEN '- All Months -' WHEN docmonth >= 1 AND docmonth <= 12 " & _
                          "THEN DATENAME(month, DATEADD(month, docmonth, -1)) END DocMonth, DID from dbo.Document where XALASKAID = @LICNUM and DOCTYPE like '%Report%'"

                Using mConn As New SqlConnection(InsCommonLib.Settings.MSSqlConStr)
                    Using mCmd As New SqlCommand(query, mConn)
                        mCmd.Parameters.Add(New SqlParameter("@LICNUM", LicenseNumber))
                        mConn.Open()
                        mAdapter.SelectCommand = mCmd
                        mAdapter.Fill(attachmentsTable)
                    End Using
                End Using
            End If

        End If

        DataGridView3.DataSource = attachmentsTable
        Label4.Text = "Found " & DataGridView3.Rows.Count & " images"
    End Sub

感谢您的帮助和时间。