parameterized query in ms access 2003 using vba
Ok. I want to use parameterized queries to avoid dealing with embedded double or single quotes (" or ') in my data.
As a simple example, what would the VBA code look like for the parameterized verio开发者_开发知识库n of this?
Dim qstr as String
Dim possiblyDangerousString as String
qstr = "SELECT MyTable.LastName from MyTable WHERE MyTable.LastName = '" & possiblyDangerousString & "';"
I did not cut and paste this from my code (on a different box right now), so there might be a typo.
Once I figure out this simple example, I need to move on to more complex statements (multiple parameters and joins). Thanks for any advice
In VBA, you can use something like:
Dim db As DAO.Database
Dim qdf As QueryDef
Dim strSQL as String
Set db = CurrentDb
strSQL = "PARAMETERS txtLastName Text(150); " _
& "SELECT LastName FROM MyTable " _
& "WHERE LastName=txtLastName"
''Create a temporary query
Set qdf = db.CreateQueryDef("", strSQL)
qdf.Parameters!txtLastName = Trim(possiblyDangerousString)
This example is not much use, because what are you going to do with the query now? Note that you can store parameter queries and assign the parameters in VBA. Note also that memo fields become a problem because a parameter can only accept 255 characters.
The only trouble with using the Replace function is that anywhere there is "'" it will replace with "''" even if you have already qualified the single quotation with another single quotation after it: "''" becomes "''''" (and so on).
You could create a procedure or function to check for "'[!']" strings and replace those using a Like:
Public Function QualifySingleQuote(myStr as string) As String
If myStr Like "*'[!']*" Then
QualifySingleQuote = Replace(myStr, "'", "''")
Else
QualifySingleQuote = myStr
EndIf
End Function
精彩评论