You need to escape the quote, like so:

'Women\'s Development & Empowerment, Youth Affairs'

Note, that if you're generating the SQL statement from a language like PHP, there are functions available to do this for you.

In PHP, for instance, there is mysql_real_escape_string, which takes care of it for you. Note, that prepared statements are to be prefered over this, as it's harder to get those wrong.

See also:

  • The MySQL manual entry on strings
  • PHP PDO prepared statements
Answer from Sebastian Paaske Tørholm on Stack Overflow
Top answer
1 of 7
141

The information provided in this answer can lead to insecure programming practices.

The information provided here depends highly on MySQL configuration, including (but not limited to) the program version, the database client and character-encoding used.

See http://dev.mysql.com/doc/refman/5.0/en/string-literals.html

MySQL recognizes the following escape sequences.
\0     An ASCII NUL (0x00) character.
\'     A single quote (“'”) character.
\"     A double quote (“"”) character.
\b     A backspace character.
\n     A newline (linefeed) character.
\r     A carriage return character.
\t     A tab character.
\Z     ASCII 26 (Control-Z). See note following the table.
\\     A backslash (“\”) character.
\%     A “%” character. See note following the table.
\_     A “_” character. See note following the table.

So you need

select * from tablename where fields like "%string \"hi\" %";

Although as Bill Karwin notes below, using double quotes for string delimiters isn't standard SQL, so it's good practice to use single quotes. This simplifies things:

select * from tablename where fields like '%string "hi" %';
2 of 7
38

I've developed my own MySQL escape method in Java (if useful for anyone).

See class code below.

Warning: wrong if NO_BACKSLASH_ESCAPES SQL mode is enabled.

private static final HashMap<String,String> sqlTokens;
private static Pattern sqlTokenPattern;

static
{           
    //MySQL escape sequences: http://dev.mysql.com/doc/refman/5.1/en/string-syntax.html
    String[][] search_regex_replacement = new String[][]
    {
                //search string     search regex        sql replacement regex
            {   "\u0000"    ,       "\\x00"     ,       "\\\\0"     },
            {   "'"         ,       "'"         ,       "\\\\'"     },
            {   "\""        ,       "\""        ,       "\\\\\""    },
            {   "\b"        ,       "\\x08"     ,       "\\\\b"     },
            {   "\n"        ,       "\\n"       ,       "\\\\n"     },
            {   "\r"        ,       "\\r"       ,       "\\\\r"     },
            {   "\t"        ,       "\\t"       ,       "\\\\t"     },
            {   "\u001A"    ,       "\\x1A"     ,       "\\\\Z"     },
            {   "\\"        ,       "\\\\"      ,       "\\\\\\\\"  }
    };

    sqlTokens = new HashMap<String,String>();
    String patternStr = "";
    for (String[] srr : search_regex_replacement)
    {
        sqlTokens.put(srr[0], srr[2]);
        patternStr += (patternStr.isEmpty() ? "" : "|") + srr[1];            
    }
    sqlTokenPattern = Pattern.compile('(' + patternStr + ')');
}


public static String escape(String s)
{
    Matcher matcher = sqlTokenPattern.matcher(s);
    StringBuffer sb = new StringBuffer();
    while(matcher.find())
    {
        matcher.appendReplacement(sb, sqlTokens.get(matcher.group(1)));
    }
    matcher.appendTail(sb);
    return sb.toString();
}
🌐
PHP
php.net › manual › en › function.mysql-real-escape-string.php
PHP: mysql_real_escape_string - Manual
Escapes special characters in the unescaped_string, taking into account the current character set of the connection so that it is safe to place it in a mysql_query(). If binary data is to be inserted, this function must be used.
🌐
sebhastian
sebhastian.com › mysql-special-characters
MySQL - How to include special characters in a query | sebhastian
December 19, 2021 - To add a newline character, use the \n escape sequence as shown below: SELECT 'Hello, my name \n is Nathan'; -- Output: -- +----------------------------+ -- | Hello, my name -- is Nathan | -- +----------------------------+ -- | Hello, my name ...
🌐
Experts Exchange
experts-exchange.com › questions › 28572879 › MySQL-escape-special-characters.html
Solved: MySQL: escape special characters | Experts Exchange
December 2, 2014 - "select * from table where column='" . mysql_real_escape_string($the_value) . "'"; "insert into table (column1, column2) values ('".mysql_real_escape_string($the_value1)."','".mysql_real_escape_string($the_value2)."')";
🌐
Chron.com
smallbusiness.chron.com › insert-commas-quotes-mysql-27985.html
How to Insert Commas & Quotes in MySQL
October 27, 2016 - Type the MySQL insert statement that inserts the characters, placing a backslash in front of any commas or quotes. The following code is an example of inserting characters using the escape backslash:insert into customers (name, address) values ...
🌐
Iditect
iditect.com › guide › mysql › data-type-escape.html
How to Use MySQL Escape Characters
INSERT INTO escape_example (text_column) VALUES ('This is a newline.\nAnd this is a tab.\t'); SELECT * FROM products WHERE product_name LIKE 'P\% off%'; -- Using escape characters SELECT * FROM users WHERE username = 'admin\' OR \'1\'=\'1'; -- Using parameterized queries PREPARE stmt FROM 'SELECT * FROM users WHERE username = ?'; SET @param = 'admin\' OR \'1\'=\'1'; EXECUTE stmt USING @param;
🌐
MySQL
dev.mysql.com › doc › refman › 8.0 › en › string-literals.html
MySQL :: MySQL 8.0 Reference Manual :: 11.1.1 String Literals
For information about these forms of string syntax, see Section 12.3.7, “The National Character Set”, and Section 12.3.8, “Character Set Introducers”. Within a string, certain sequences have special meaning unless the NO_BACKSLASH_ESCAPES SQL mode is enabled.
🌐
MySQL
dev.mysql.com › doc › c-api › 5.7 › en › mysql-real-escape-string-quote.html
MySQL :: MySQL 5.7 C API Developer Guide :: 5.4.56 mysql_real_escape_string_quote()
The following example inserts two escaped strings into an INSERT statement, each within single quote characters: char query[1000],*end; end = my_stpcpy(query,"INSERT INTO test_table VALUES('"); end += mysql_real_escape_string_quote(&mysql,end,"What is this",12,'\''); end = my_stpcpy(end,"','"); end += mysql_real_escape_string_quote(&mysql,end,"binary data: \0\r\n",16,'\''); end = my_stpcpy(end,"')"); if (mysql_real_query(&mysql,query,(unsigned int) (end - query))) { fprintf(stderr, "Failed to insert row, Error: %s\n", mysql_error(&mysql)); }
Find elsewhere
🌐
Stack Overflow
stackoverflow.com › questions › 30575905 › are-there-any-scope-that-escape-all-special-characters-in-mysql-query
Are there any scope that escape all special characters in mysql query? - Stack Overflow
Randoms data may have any special ... the wording to make it easier to understand what you mean? ... No, there is no "scope" in MySQL to automatically escape ......
🌐
MySQL
dev.mysql.com › doc › en › string-literals.html
MySQL :: MySQL 9.7 Reference Manual :: 11.1.1 String Literals
For information about these forms of string syntax, see Section 12.3.7, “The National Character Set”, and Section 12.3.8, “Character Set Introducers”. Within a string, certain sequences have special meaning unless the NO_BACKSLASH_ESCAPES SQL mode is enabled.
🌐
TutorialsPoint
tutorialspoint.com › how-do-i-insert-a-special-character-such-as-single-quote-into-mysql
How do I insert a special character such as ' (single quote) into MySQL?
To insert a special character such as “ ‘ “ (single quote) into MySQL, you need to use \’ escape character. The syntax is as follows − · insert into yourTableName(yourColumnName) values(' yourValue\’s '); To understand the above syntax, let us create two tables. The query to create first table is as follows −
🌐
TutorialsPoint
tutorialspoint.com › How-can-we-escape-special-characters-in-MySQL-statement
How can we escape special characters in MySQL statement?
June 22, 2020 - Sometimes we need to include special ... basic rules for escaping special characters which are given below − · mysql> Select 'A\B'; +-----+ | A\B | +-----+ | A\B | +-----+ 1 row in set (0.00 sec)...
🌐
Stack Overflow
stackoverflow.com › questions › 25397971 › how-to-escape-special-characters-during-insertion-in-python-mysql
How to Escape special characters during insertion in python-mysql? - Stack Overflow
... Specifically, use your DB API to properly escape the special characters by passing your parameters to it in the format it expects (a tuple of values) rather than relying on string interpolation to build the query string.
🌐
Stack Overflow
stackoverflow.com › questions › 13227656 › escaping-special-characters-while-inserting-in-mysql
Escaping special characters while inserting in mysql - Stack Overflow
I am inserting multi-rows in a mysql database by concating values as in the query INSERT INTO tableName (col1, col2, col3) VALUES('a', 'b', 'c'), ('d', 'b', 'c'), ('e', 'b', 'c'); However, someti...
Top answer
1 of 4
18

This is one of the reasons you're supposed to use parameter binding instead of formatting the parameters in Python.

Just do this:

sql = 'UPGRADE inventory_server set server_mac = %s where server_name = %s'

Then:

cur.execute(sql, macs, host)

That way, you can just deal with the string as a string, and let the MySQL library figure out how to quote and escape it for you.

On top of that, you generally get better performance (because MySQL can compile and cache one query and reuse it for different parameter values) and avoid SQL injection attacks (one of the most common ways to get yourself hacked).

2 of 4
7

Welcome to the world of string encoding formats!

tl;dr - The preferred method for handling quotes and escape characters when storing data in MySQL columns is to use parameterized queries and let the MySQLDatabase driver handle it. Alternatively, you can escape quotes and slashes by doubling them up prior to insertion.

Full example at bottom of link

standard SQL update

# as_json must have escape slashes and quotes doubled
query = """\
        UPDATE json_sandbox
        SET data = '{}'
        WHERE id = 1;
    """.format(as_json)

with DBConn(*client.conn_args) as c:
    c.cursor.execute(query)
    c.connection.commit()

parameterized SQL update

# SQL Driver will do the escaping for you
query = """\
        UPDATE json_sandbox
        SET data = %s
        WHERE id = %s;
    """

with DBConn(*client.conn_args) as c:
    c.cursor.execute(query, (as_json, 1))
    c.connection.commit()

Invalid JSON SQL

{
  "abc": 123,
  "quotes": "ain't it great",
  "multiLine1": "hello\nworld",
  "multiLine3": "hello\r\nuniverse\r\n"
}

Valid JSON SQL

{
  "abc": 123,
  "quotes": "ain''t it great",
  "multiLine1": "hello\\nworld",
  "multiLine3": "hello\\r\\nuniverse\\r\\n"
}

Python transform:

# must escape the escape characters, so each slash is doubled
# Some MySQL Python libraries also have an escape() or escape_string() method.
as_json = json.dumps(payload) \
    .replace("'", "''") \
    .replace('\\', '\\\\')

Full example

import json
import yaml

from DataAccessLayer.mysql_va import get_sql_client, DBConn

client = get_sql_client()

def encode_and_store(payload):
    as_json = json.dumps(payload) \
        .replace("'", "''") \
        .replace('\\', '\\\\')

    query = """\
            UPDATE json_sandbox
            SET data = '{}'
            WHERE id = 1;
        """.format(as_json)

    with DBConn(*client.conn_args) as c:
        c.cursor.execute(query)
        c.connection.commit()

    return

def encode_and_store_2(payload):
    as_json = json.dumps(payload)

    query = """\
            UPDATE json_sandbox
            SET data = %s
            WHERE id = %s;
        """

    with DBConn(*client.conn_args) as c:
        c.cursor.execute(query, (as_json, 1))
        c.connection.commit()

    return


def retrieve_and_decode():
    query = """
        SELECT * FROM json_sandbox
        WHERE id = 1
    """

    with DBConn(*client.conn_args) as cnx:
        cursor = cnx.dict_cursor
        cursor.execute(query)

        rows = cursor.fetchall()


    as_json = rows[0].get('data')

    payload = yaml.safe_load(as_json)
    return payload



if __name__ == '__main__':

    payload = {
        "abc": 123,
        "quotes": "ain't it great",
        "multiLine1": "hello\nworld",
        "multiLine2": """
            hello
            world
        """,
        "multiLine3": "hello\r\nuniverse\r\n"
    }


    encode_and_store(payload)
    output_a = retrieve_and_decode()

    encode_and_store_2(payload)
    output_b = retrieve_and_decode()

    print("original: {}".format(payload))
    print("method_a: {}".format(output_a))
    print("method_b: {}".format(output_b))

    print('')
    print(output_a['multiLine1'])

    print('')
    print(output_b['multiLine2'])

    print('\nAll Equal?: {}'.format(payload == output_a == output_b))

🌐
MySQL
dev.mysql.com › doc › c-api › 8.4 › en › mysql-real-escape-string.html
MySQL :: MySQL 8.4 C API Developer Guide :: 5.4.60 mysql_real_escape_string()
The following example inserts two escaped strings into an INSERT statement, each within single quote characters: char query[1000],*end; end = my_stpcpy(query,"INSERT INTO test_table VALUES('"); end += mysql_real_escape_string(&mysql,end,"What is this",12); end = my_stpcpy(end,"','"); end += mysql_real_escape_string(&mysql,end,"binary data: \0\r\n",16); end = my_stpcpy(end,"')"); if (mysql_real_query(&mysql,query,(unsigned int) (end - query))) { fprintf(stderr, "Failed to insert row, Error: %s\n", mysql_error(&mysql)); }
🌐
Linux Hint
linuxhint.com › escape-string-mysql
Escape string in MySQL – Linux Hint
SELECT QUOTE('MySQL''Database''Server' ) AS Escaped_Value; ... The following output will appear after executing the above query.