views:

68

answers:

2

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  A: 

You haven't told us what library or DB you are using, but I think your question is answered here: http://stackoverflow.com/questions/309945/how-to-quote-a-string-value-explicitly-python-db-api-psycopg2

spookylukey
seems to be just what i need!
Claudiu
+3  A: 

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",))
Rob Kruus
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.
Forest
but.. what if i want to transmogrify instead?
Claudiu