A good way to escape quotes in a database query string?

If it's part of a Database query you should be able to use a Parameterized SQL Statement.

As well as escaping your quotes, this will deal with all special characters and will protect you from SQL injection attacks.


Use json.dumps.

>>> import json
>>> print json.dumps('a"bc')
"a\"bc"

The easy and standard way to escape strings, and convert other objects to programmatic form, is to use the built in repr() function. It converts an object into the representation you would need to enter it with manual code.

E.g.:

s = "I'm happy I am \"here\" now"
print repr(s)
>>  'I\'m happy I am "here" now'

No weird hacks, it's built in and it just works for most purposes.


Triple single quotes will conveniently encapsulate the single quotes often used in SQL queries:

c.execute('''SELECT sval FROM sdat WHERE instime > NOW() - INTERVAL '1 days' ORDER BY instime ASC''')

If using psycopg2, its execute() method has built-in escaping:

cursor.execute("SELECT column FROM table WHERE column=%s AND column2=%s", (value1, value2))

Note, that you are giving two arguments to execute method (string and tuple), instead of using Python's % operator to modify string.

Answer stolen from here: psycopg2 equivalent of mysqldb.escape_string?