How to see the real SQL query in Python cursor.execute using pyodbc and MS-Access

philnext picture philnext · Mar 10, 2011 · Viewed 81.6k times · Source

I use the following code in Python (with pyodbc for a MS-Access base).

cursor.execute("select a from tbl where b=? and c=?", (x, y))

It's Ok but, for maintenance purposes, I need to know the complete and exact SQL string send to the database.
Is it possible and how ?

Answer

samplebias picture samplebias · Mar 10, 2011

It differs by driver. Here are two examples:

import MySQLdb
mc = MySQLdb.connect()
r = mc.cursor()
r.execute('select %s, %s', ("foo", 2))
r._executed
"select 'foo', 2"

import psycopg2
pc = psycopg2.connect()
r = pc.cursor()
r.execute('select %s, %s', ('foo', 2))
r.query
"select E'foo', 2"