如何使用Python在Sqlite3中记录查询? [英] How can I log queries in Sqlite3 with Python?
问题描述
我正在Python应用程序中使用Sqlite3数据库,并使用参数替换对其进行查询.
例如:
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,))
某些查询无法正确返回结果,我想将其记录下来并尝试手动查询sqlite.
如何使用参数而不是问号记录这些查询?
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具有 sqlite3.Connection.set_trace_callback :
Python 3.3 has sqlite3.Connection.set_trace_callback:
import sqlite3
connection = sqlite3.connect(':memory:')
connection.set_trace_callback(print)
通过该特定Connection对象执行的每个SQL语句都将调用您作为参数提供的函数.您可能要使用 logging
模块中的函数来代替 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.
这篇关于如何使用Python在Sqlite3中记录查询?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!