问题
When I have a cursor, I know I can safely execute a query as follows:
cur.execute("SELECT * FROM foo WHERE foo.bar = %s", (important_variable,))
Is there any way to just get the string safely without executing the query? For example, if important_variable
is a string, like "foo 'bar' \"baz"
, I'd want the appropriately escaped one:
"SELECT * FROM foo WHERE foo.bar = "foo \'bar\' \"baz"
(or whatever the appropriate escaping is, I'm not even sure).
I'm using psycopg, and sqlobject.
回答1:
Look at the mogrify method for cursors -- it will return the string after variable binding and show any quoting it does
cur.mogrify("SELECT * FROM foo WHERE foo.bar = %s", ("foo 'bar' \"baz",))
回答2:
You haven't told us what library or DB you are using, but I think your question is answered here: How to quote a string value explicitly (Python DB API/Psycopg2)
回答3:
SQLObject handles escaping/quoting itself, but if you want to use that functionality:
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'
来源:https://stackoverflow.com/questions/3111721/python-get-escaped-sql-string