How to escape apostrophe (') in MySql?

前端 未结 10 632
孤城傲影
孤城傲影 2020-11-22 07:49

The MySQL documentation says that it should be \\\'. However, both scite and mysql shows that \'\' works. I saw that and it works. What should I d

相关标签:
10条回答
  • 2020-11-22 08:04

    Here's an example:

    SELECT * FROM pubs WHERE name LIKE "%John's%"
    

    Just use double quotes to enclose the single quote.

    If you insist in using single quotes (and the need to escape the character):

    SELECT * FROM pubs WHERE name LIKE '%John\'s%'
    
    0 讨论(0)
  • 2020-11-22 08:08

    Standard SQL uses doubled-up quotes; MySQL has to accept that to be reasonably compliant.

    'He said, "Don''t!"'
    
    0 讨论(0)
  • 2020-11-22 08:10

    What I believe user2087510 meant was:

    name = 'something'
    name = name.replace("'", "\\'")
    

    I have also used this with success.

    0 讨论(0)
  • 2020-11-22 08:11

    The MySQL documentation you cite actually says a little bit more than you mention. It also says,

    A “'” inside a string quoted with “'” may be written as “''”.

    (Also, you linked to the MySQL 5.0 version of Table 8.1. Special Character Escape Sequences, and the current version is 5.6 — but the current Table 8.1. Special Character Escape Sequences looks pretty similar.)

    I think the Postgres note on the backslash_quote (string) parameter is informative:

    This controls whether a quote mark can be represented by \' in a string literal. The preferred, SQL-standard way to represent a quote mark is by doubling it ('') but PostgreSQL has historically also accepted \'. However, use of \' creates security risks...

    That says to me that using a doubled single-quote character is a better overall and long-term choice than using a backslash to escape the single-quote.

    Now if you also want to add choice of language, choice of SQL database and its non-standard quirks, and choice of query framework to the equation, then you might end up with a different choice. You don't give much information about your constraints.

    0 讨论(0)
  • 2020-11-22 08:11

    just write '' in place of ' i mean two times '

    0 讨论(0)
  • 2020-11-22 08:14

    I think if you have any data point with apostrophe you can add one apostrophe before the apostrophe

    eg. 'This is John's place'

    Here MYSQL assumes two sentence 'This is John' 's place'

    You can put 'This is John''s place'. I think it should work that way.

    0 讨论(0)
提交回复
热议问题