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

Viewed 113737

I've tried all manner of Python modules and they either escape too much or in the wrong way. What's the best way you've found to escape quotes (", ') in Python?

9 Answers

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''')

For a solution to a more generic problem, I have a program where I needed to store any set of characters in a flat file, tab delimited. Obviously, having tabs in the 'set' was causing problems.

Instead of output_f.write(str), I used output_f.write(repr(str)), which solved my problem. It is slower to read, as I need to eval() the input when I read it, but overall, it makes the code cleaner because I don't need to check for fringe cases anymore.

For my use case, I was saving a paragraph against the database and somewhere in the paragraph there might have been some text with a single quote (example: Charlie's apple sauce was soggy)

I found this to work best:

database_cursor.execute('''INSERT INTO books.collection (book_name, book_quoted_text) VALUES ('%s', "%s")''' % (book_name, page_text.strip()))

You'll notice that I use "" after wrapping the INSERT statement in '''

Related