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?
The simplest method to escape single quotes in SQL is to use two single quotes. For example, if you wanted to show the value O'Reilly, you would use two quotes in the middle instead of one. The single quote is the escape character in Oracle, SQL Server, MySQL, and PostgreSQL.
Use two single quotes to escape them in the sql statement. The double quotes should not be a problem: SELECT 'How is my son''s school helping him learn? "Not as good as Stack Overflow would!"'
You can put a backslash character followed by a quote ( \" or \' ). This is called an escape sequence and Python will remove the backslash, and put just the quote in the string. Here is an example. The backslashes protect the quotes, but are not printed.
Use braces to escape a string of characters or symbols. Everything within a set of braces in considered part of the escape sequence. When you use braces to escape a single character, the escaped character becomes a separate token in the query. Use the backslash character to escape a single character or symbol.
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 you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With