25

I'm using Sqlite3 database in my Python application and query it using parameters substitution.
For example:

cursor.execute('SELECT * FROM table WHERE id > ?', (10,))

Some queries do not return results properly and I would like to log them and try to query sqlite manually.
How can I log these queries with parameters instead of question marks?

gennad
  • 5,335
  • 12
  • 44
  • 47
  • Looks similar to [this](http://stackoverflow.com/questions/1607368/sql-query-logging-for-sqlite) question, though that example doesn't specify Python. See if it helps. – thegrinner Aug 04 '11 at 13:18

2 Answers2

38

Python 3.3 has sqlite3.Connection.set_trace_callback:

import sqlite3
connection = sqlite3.connect(':memory:')
connection.set_trace_callback(print)

The function you provide as argument gets called for every SQL statement that is executed through that particular Connection object. Instead of print, you may want to use a function from the logging module.

Marcel M
  • 1,244
  • 12
  • 19
  • Will that log query info for all queries or just for those of my own app? – TaW Nov 14 '18 at 08:37
  • 1
    It’ll log only those queries made through that particular Connection object (`connection` above). I’ve update the answer. – Marcel M Nov 14 '18 at 10:32
  • 2
    If you're using the logging infrastructure it's worth noting you can replace "print" with say "logging.debug" seamlessly. – kristopolous May 31 '19 at 07:43
0

Assuming that you have a log function, you could call it first :

query, param = 'SELECT * FROM table WHERE id > ?', (10,)
log(query.replace('?', '%s') % param)
cursor.execute(query, param)  

So you don't modify your query at all.

Moreover, this is not Sqlite specific.

dugres
  • 12,613
  • 8
  • 46
  • 51