Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 673
Jonathan Prior Avatar asked May 22 '09 09:05

Jonathan Prior


People also ask

How do you escape quotes in SQL query?

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.

How escape double quotes in SQL query?

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!"'

How do you escape a quote?

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.

How do I escape a special character in SQL query?

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.


4 Answers

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.

like image 170
Dave Webb Avatar answered Oct 21 '22 03:10

Dave Webb


Use json.dumps.

>>> import json
>>> print json.dumps('a"bc')
"a\"bc"
like image 32
eddie_c Avatar answered Oct 21 '22 02:10

eddie_c


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.

like image 12
GregD Avatar answered Oct 21 '22 03:10

GregD


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''')
like image 4
Roy Avatar answered Oct 21 '22 03:10

Roy