如何在vb.net中参数化sql语句?

时间:2014-02-21 07:24:25

标签: sql-server vb.net

我有以下SQL语句来搜索表中的记录并将它们存储在名为“lvw”的列表视图中。我应该如何将其转换为参数化语句以防止SQL注入攻击?谢谢

            con.Open()
                Dim da As New SqlDataAdapter("Select * from Students " & _
                   "where student_id like '%" & Me.srcTxt.Text.Trim & "%' " & _
                   "or " & _
                 "student_firstname like '%" & Me.srcTxt.Text.Trim & "%' " & _
                 "or " & _
               "student_lastname like '%" & Me.srcTxt.Text.Trim & "%'", con)

               da.Fill(ds)
               con.Close()

        For i As Integer = 0 To ds.Tables(0).Rows.Count - 1
              Dim lvi As New ListViewItem
              lvi.Text = ds.Tables(0).Rows(i)(0).ToString()
                   For j As Integer = 1 To ds.Tables(0).Rows(i).ItemArray.Length - 1
                       lvi.SubItems.Add(ds.Tables(0).Rows(i)(j).ToString())
                   Next
               lvw.Items.Add(lvi)
         Next

1 个答案:

答案 0 :(得分:1)

只需在字符串中放置参数,然后将适当的值添加到适配器的SelectCommand

Dim da As New SqlDataAdapter("Select * from Students " & _
               "where student_id like @searchTerm " & _
               "or " & _
             "student_firstname like @searchTerm " & _
             "or " & _
           "student_lastname like @searchTerm", con)
da.SelectCommand.Parameters.AddWithValue("@searchTerm", _
            "%" + Me.srcTxt.Text.Trim + "%")