开发者

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.ex开发者_运维知识库ecute('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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜