[英]How to retrieve executed SQL code from SQLAlchemy
I am using SQLAlchemy and would like to log executed SQL code (ie the code with all bind parameters already quoted and replaced).我正在使用 SQLAlchemy 并想记录执行的 SQL 代码(即所有绑定参数已被引用和替换的代码)。 In case of psycopg2 it was possible using the
query
attribute of the Cursor
object (see psycopg documentation ).在psycopg2的情况下,可以使用
Cursor
object 的query
属性(参见psycopg 文档)。 In case of MySQLdb it is possible using the _last_executed
attribute of the Cursor
object.在MySQLdb的情况下,可以使用
Cursor
object 的_last_executed
属性。
My question is: How can I retrieve the just executed query string using SQLAlchemy interfaces?我的问题是:如何使用 SQLAlchemy 接口检索刚刚执行的查询字符串? Does it provide such functionality or should I write my own helper function?
它提供这样的功能还是我应该编写自己的助手 function?
Thanks in advance for any help.提前感谢您的帮助。
SQLAlchemy uses the standard Python logging library . SQLAlchemy 使用标准的 Python 日志库。 To log queries to a file named
db.log
:要将查询记录到名为
db.log
的文件中:
import logging
logging.basicConfig(filename='db.log')
logging.getLogger('sqlalchemy.engine').setLevel(logging.INFO)
When using Python logging, ensure all echo
flags are set to False
, to avoid duplicate logging.使用 Python 日志记录时,确保所有
echo
显标志都设置为False
,以避免重复记录。 Now add something to the db:现在向数据库添加一些东西:
>>> Movie(title=u"Blade Runner", year=1982)
>>> session.commit()
Which will log something like:这将记录如下内容:
INFO:sqlalchemy.engine.base.Engine:BEGIN (implicit)
INFO:sqlalchemy.engine.base.Engine:INSERT INTO models_movie (title, year, description) VALUES (%(title)s, %(year)s, %(description)s) RETURNING models_movie.id
INFO:sqlalchemy.engine.base.Engine:{'title': u'Blade Runner', 'description': None, 'year': 1982}
INFO:sqlalchemy.engine.base.Engine:COMMIT
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.