Adding Parameters to OleDBConnection

蓝咒 提交于 2019-12-13 02:26:36

问题


I'm executing the below to run a query from an Access DB.

  Dim search As String = txtUnitCode.Text
    Dim sText As String = String.Empty
    Dim aClients As String = My.Settings.ClientDB
    Dim sConnString As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data source=" & aClients & ""

    Using cn As New OleDb.OleDbConnection(sConnString)
        cn.Open()
        If txtUnitCode.Text = "" Then Exit Sub
        Dim cmd As New OleDb.OleDbCommand("SELECT Name FROM Units WHERE (Code = " & search & ") ", cn)


        Dim r As OleDb.OleDbDataReader = cmd.ExecuteReader()
        If Not r.HasRows Then Exit Sub

        Do While r.Read()
            sText = sText & r.GetString(0)
        Loop

    End Using
txtUnitName.Text = sText

When i run the code analysis in VS it indicates a vulnerability in this line

Dim cmd As New OleDb.OleDbCommand("SELECT Name FROM Units WHERE (Code = " & search & ") ", cn)

and basically I think its suggesting that the search part of the code should ideally be a Parameter. I have got these to work with another code using OleDbDataAdapter but can't fathom it with a OleDbConnection

Any pointers

Thanks


回答1:


Connections don't have parameters. You could use the OleDbConnectionStringBuilder class to build your connection string.

But for the Command object, yes, always use parameters to avoid SQL injection:

Dim cmd As New OleDb.OleDbCommand("SELECT Name FROM Units WHERE Code = @code", cn)
cmd.Parameters.AddWithValue("@code", search)

Do note that the OleDb library doesn't actually use the @code name signature, it will fill in the parameters in index order, so you could replace @code with just a question mark (?).



来源:https://stackoverflow.com/questions/23689213/adding-parameters-to-oledbconnection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!