简体   繁体   中英

How can I log queries in Sqlite3 with Python?

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?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM