Python: get SQL escape string

When I have a cursor, I know that I can safely execute the request as follows:

cur.execute("SELECT * FROM foo WHERE foo.bar = %s", (important_variable,))

Is there a way to just get the string safely without executing the query? For example, if important_variableis a string, for example "foo 'bar' \"baz", I would like it to be appropriately escaped:

"SELECT * FROM foo WHERE foo.bar = "foo \'bar\' \"baz"

(or whatever happens, I'm not even sure).

I am using psycopg and sqlobject.

+3
source share
3 answers

Look at the mogrify method for cursors - it will return the string after binding the variable and show any quote from it.

cur.mogrify("SELECT * FROM foo WHERE foo.bar = %s", ("foo 'bar' \"baz",))
+4
source
+1

SQLObject handles escaping / quoting, but if you want to use this function:

from sqlobject.converters import sqlrepr
print(sqlrepr('SELECT * FROM foo WHERE foo.bar = "foo \'bar\' \"baz', 'postgres'))

Result:

'SELECT * FROM foo WHERE foo.bar = "foo ''bar'' "baz'
0
source

Source: https://habr.com/ru/post/1751611/


All Articles