向OleDBConnection添加参数 [英] Adding Parameters to OleDBConnection

查看:130
本文介绍了向OleDBConnection添加参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在执行以下操作,以从Access DB运行查询.

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

当我在VS中运行代码分析时,表明此行存在漏洞

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)

,基本上我认为这表明代码的search部分在理想情况下应为Parameter.我已经将它们与使用OleDbDataAdapter的另一个代码一起使用,但是无法通过OleDbConnection

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

任何指针

谢谢

推荐答案

连接没有参数.您可以使用OleDbConnectionStringBuilder类来构建您的连接字符串.

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

但是对于Command对象,是的,请始终使用参数来避免SQL注入:

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)

请注意,OleDb库实际上并不使用@code名称签名,它会按索引顺序填充参数,因此您可以仅用问号(?)替换@code.

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

这篇关于向OleDBConnection添加参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆