Reputation: 4534
The advised way to run a parameterized query with psycopg2, if I understand correctly, is to use the second argument to the execute method:
SQL = "INSERT INTO authors (name) VALUES (%s);"
data = ("O'Reilly", )
cur.execute(SQL, data)
This will sanitize the data, do quoting, etc. That's great. Less great is it appears to be opaque; it seems to be a black box that modifies my code. I'd like to see what the actual query sent to the database is. Is there some way to see that?
Upvotes: 1
Views: 238
Reputation: 55630
You can use the cursor.mogrify method to print the query with interpolated values:
>>> conn = psycopg2.connect(database='test')
>>> cur = conn.cursor()
>>> cur.mogrify('SELECT foo, bar, baz FROM quux WHERE a = %s', (42,))
b'SELECT foo, bar, baz FROM quux WHERE a = 42'
Note that this is a psycopg2-specific method - it won't work for other DB-API connectors.
Upvotes: 3