在VB.Net上使用参数化查询填充ListBox

时间:2014-12-11 03:30:55

标签: sql-server vb.net data-binding

我有以下代码,涉及填充ListBox。如何参数化查询以防止SQL注入?

    sqlCon = New SqlConnection(strConn)
    sqlCon.Open()
    Dim sql As String = "SELECT * FROM employees where id = & textbox1.text &"
    Dim adapter As New SqlDataAdapter(sql, sqlCon)
    Dim da As New DataTable
    adapter.Fill(da)
    ListBox1.DisplayMember = "employees"
    ListBox1.DataSource = da
    ListBox1.ValueMember = "employees"
    sqlCon.Close()

1 个答案:

答案 0 :(得分:0)

也许这会有所帮助:

Using sqlCon As SqlConnection = New SqlConnection(strConn)
    sqlCon.Open()
    Dim sql As String = "SELECT * FROM employees WHERE id = @id"
    Dim adapter As SqlDataAdapter = New SqlDataAdapter(sql, sqlCon)
    adapter.SelectCommand.Parameters.Add(New SqlParameter("@id", textbox1.Text))

    Dim da As New DataTable
    adapter.Fill(da)

    ListBox1.DisplayMember = "employees"
    ListBox1.DataSource = da
    ListBox1.ValueMember = "employees"
End Using

最好将代码放在Using中,以便即使抛出异常也会处置SqlConnection。另外,您可能需要指定列名称,而不是使用SELECT *