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\'
I'd check cursor._last_executed afterwards, but if you want them printed out in real time without changing every execute try this monkey patch:
def log_queries(cur):
def _query(q):
print q # could also use logging
return cur._do_query(q)
cur._query = _query
conn = MySQLdb.connect( read_default_file='~/.my.cnf' )
cur = conn.cursor()
log_queries(cur)
cur.execute('SELECT %s, %s, %s', ('hello','there','world'))
It's very dependent on MySQLdb (and could break in later versions). It works because cur._query currently simply calls calls._do_query and returns its result.
Write the sql string and then execute it:
sql='''select a
from tbl
where b=?
and c=? '''
cursor.execute(sql, x, y)
print 'just executed:',(sql, x,y)
Now you can do whatever you want with the SQL statement.
Since pyodbc doesn't have a way to see the query BEFORE it is executed. You can pre-populate the query manually just to get an idea of what it will end up looking like. It's not going to work as the actual query, but it helped me figure out if I had any errors in a query that needed more than 40 parameters.
query = """select * from [table_name] where a = ? and b = ?"""
parameter_list = ['dog', 'cat'] # List of parameters, a = 'dog', b = 'cat'.
query_list = list(query) # Split query string into individual characters.
# Loop through list and populate the question marks.
for i in range(len(parameter_list)):
for idx, val in enumerate(query_list):
if val == '?':
query_list[idx] = str(parameter_list[i])
break
# Rejoin the query string.
query_populate = ''.join(query_list)
#### Result ####
"""select * from [table_name] where a = dog and b = cat"""