在Python中打印SQLAlchemy查询

时间:2015-11-16 14:33:13

标签: python sql sqlalchemy

我需要知道使用值打印SQLAlchemy查询的方法。

我可以打印正在处理的查询,但它没有显示值而只是显示字段名称本身。

SELECT recordsets.id AS recordsets_id, recordsets.version AS recordsets_version
FROM recordsets 
WHERE recordsets.domain_id = :domain_id_1 
AND recordsets.tenant_id IN (:tenant_id_1, :tenant_id_2) 
AND recordsets.name IN (:name_1, :name_2)

因此,而不是:name_1,:name_2或:tenant_id_1,:tenant_id_2我需要查看值本身。

1 个答案:

答案 0 :(得分:0)

当您创建引擎时,可以通过在echo上设置True来启用日志记录。这将打印所有查询及其参数。

示例:

engine = create_engine("mysql://scott:tiger@hostname/dbname",
                        encoding='latin1', echo=True)

请参阅:http://docs.sqlalchemy.org/en/rel_1_0/core/engines.html#engine-creation-api

对于您的示例,输出将如下所示:

2015-11-16 15:50:25,137 INFO sqlalchemy.engine.base.Engine SELECT recordsets.id AS recordsets_id, recordsets.version AS recordsets_version
FROM recordsets 
WHERE recordsets.domain_id = :domain_id_1 
AND recordsets.tenant_id IN (:tenant_id_1, :tenant_id_2) 
AND recordsets.name IN (:name_1, :name_2)
2015-11-16 15:50:25,137 INFO sqlalchemy.engine.base.Engine {'domain_id_1': 'THE actual domain id', 'tenant_id_1': 234, 'tenant_id_2': 456, 'name_1': 'your first name', 'name_2': 'your second example name'}