Escape string Python for MySQL Escape string Python for MySQL python python

Escape string Python for MySQL


The MySQLdb library will actually do this for you, if you use their implementations to build an SQL query string instead of trying to build your own.

Don't do:

sql = "INSERT INTO TABLE_A (COL_A,COL_B) VALUES (%s, %s)" % (val1, val2)cursor.execute(sql)

Do:

sql = "INSERT INTO TABLE_A (COL_A,COL_B) VALUES (%s, %s)"cursor.execute(sql, (val1, val2))


>>> import MySQLdb>>> example = r"""I don't like "special" chars ¯\_(ツ)_/¯""">>> example'I don\'t like "special" chars \xc2\xaf\\_(\xe3\x83\x84)_/\xc2\xaf'>>> MySQLdb.escape_string(example)'I don\\\'t like \\"special\\" chars \xc2\xaf\\\\_(\xe3\x83\x84)_/\xc2\xaf'