Escaping unwanted characters, mainly single quotes --replace function and implementation

前端 未结 3 1851
礼貌的吻别
礼貌的吻别 2021-01-18 07:02

I was just testing my database and I realized that I run into problems wherever a text entry in my database contains a \' character (single quote). My solution

3条回答
  •  离开以前
    2021-01-18 07:49

    First examine these 2 lines.

    "VALUES ( " & "'" & me.testparam & "'" & ");"
    "VALUES ( '" & me.testparam & "');"
    

    Both will produce the exact same string. The difference for me is that my brain comprehends the second version faster.

    Now, here is what the comments are telling you to do ... replace each single quote in your source string with two single quotes. I added Debug.Print so you can view the finished string in the Immediate window (go there with Ctrl+g) ... you can then see the actual string rather than trying to imagine what it looks like.

    qr = "INSERT INTO tblExample VALUES ( '" & _
        Replace(Me.testparam, "'", "''" & "');"
    Debug.Print qr
    db.Execute qr, dbFailOnError 
    

    Since I assumed db is a DAO.Database object variable, I included the dbFailOnError option. You should include an error handler in your code to deal with any problems dbFailOnError exposes.

    When you run into trouble with a VBA function in a query, drop to the Immediate window and test your function expression there. This one triggers a compile error, "Expected: list separator or )":

    ? Replace("Tourette's", "'", " "'" ")
    

    But this one works:

    ? Replace("Tourette's", "'", "''")
    Tourette''s
    

    I mentioned that because it's useful in general, and also because your title starts with "Escaping unwanted characters, mainly single quotes". So if you want to remove/replace other characters, not just single quotes, experiment in the Immediate window until you find a Replace() expression which works. Then use that expression in your query.

    For example, if unwanted characters include line breaks ...

    MyString = "foo" & vbCrlf & "bar" : ? MyString
    foo
    bar
    ? Replace(MyString, Chr(13) & Chr(10), " ")
    foo bar
    

    Note: I used Chr(13) & Chr(10) rather than vbCrlf as the find target because the db engine can use the Chr() function but doesn't know about the named constant (vbCrlf).

提交回复
热议问题