1

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.

2
  • 1
    If important_variable is datetime.date(2000,1,1) then I think Claudiu wants a function which returns the string "SELECT * FROM foo WHERE foo.bar = '2000-1-1'" Commented Jun 24, 2010 at 16:17
  • 1
    Actually there is no escaping involved in this case - the driver sends the parametrized statement and the arguments separately. OTOH check psycopg2.extensions.QuotedString if you're using psycopg2. Commented Jun 24, 2010 at 16:21

3 Answers 3

4

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",))
Sign up to request clarification or add additional context in comments.

2 Comments

Also note that any approach you find will be connector-specific. The DB API does not define a standard way to generate escaped SQL strings. This is appropriate because connectors don't necessarily build up the whole string on the client side; some are capable of sending the query template and the values to the server separately.
but.. what if i want to transmogrify instead?
1

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)

1 Comment

seems to be just what i need!
1

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'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.