如何在Word VBA SQL查询中处理单引号?

时间:2010-10-20 05:37:16

标签: sql vba ms-word

我从下拉列表中获取客户名称并使用该值查询Excel电子表格,但是,该名称可以包含单引号(例如:Adam's Meat)。这会破坏我的应用程序,如何使用包含单引号的变量进行查询?

Private Sub cboCompany_Change()
            Dim customerName As String
            customerName = cboCompany.Value

rsT.Open "SELECT Customer, Postcode, Address1, Address2, State, Country FROM Customers WHERE  Customer = '" & customerName & "'", cn, adOpenStatic

2 个答案:

答案 0 :(得分:7)

如果您指定两个单引号'',则一个将转义另一个并且将导致单引号,尝试将其替换为:

customerName = Replace(customerName, "'", "''")

答案 1 :(得分:7)

这使您对SQL注入攻击持开放态度。我建议将此更改为参数化查询,如此

Dim cmd as NEW ADODB.Command

With cmd
 .CommandText=”SELECT foo from tblBar where foo=?”
 .Parameters.Append .CreateParameter("@foo", adVarChar, adParamInput, 50, “What ever you want”)
 .ActiveConnection=dbCon
 .CommandType=adCmdText
End With

Set rst=cmd.execute