2014-12-11 57 views
1

我有以下代碼,涉及填充ListBox。我如何參數化查詢以防止SQL注入?使用VB.Net上的參數化查詢填充ListBox

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() 

回答

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 *,您可能需要指定列名稱。