sqlachemy 原生sql输出
- 在创建引擎时,将echo参数配置成True,会输出sql执行语句记录。默认False
create_engine(statsticConf.sqlalchemy_mysql,connect_args={"charset": "utf8mb4"},echo = True)
#输出如下:2018-12-11 15:34:31,814 INFO sqlalchemy.engine.base.Engine SELECT count(`MT4_TRADES`.`TICKET`) AS deal_close
FROM `MT4_TRADES`
WHERE `MT4_TRADES`.`LOGIN` = %(LOGIN_1)s AND `MT4_TRADES`.`CMD` IN (%(CMD_1)s, %(CMD_2)s) AND `MT4_TRADES`.`CLOSE_TIME` >= %(CLOSE_TIME_1)s AND `MT4_TRADES`.`CLOSE_TIME` < %(CLOSE_TIME_2)s
2018-12-11 15:34:31,814 INFO sqlalchemy.engine.base.Engine {'LOGIN_1': 2021400, 'CMD_1': 0, 'CMD_2': 1, 'CLOSE_TIME_1': '1970-01-01 00:00:00.1', 'CLOSE_TIME_2': '2018-10-26 09:47:00.0'}我们需要复制sql到数据库验证有效性。从结果来看,并不能直接复制到数据库执行,变量值需要手动修改代入。
- 改进。官方有提供compile方法。 https://docs.sqlalchemy.org/en/latest/core/internals.html?highlight=statement%20compile#sqlalchemy.engine.interfaces.Compiled
-
t_tradesTable = session.query(sqlQuery.label(quotaValue)).filter( sqlFilter ) print(t_tradesTable.statement.compile(compile_kwargs={'literal_binds': True}))
SELECT count(`MT4_TRADES`.`TICKET`) AS deal_close
FROM `MT4_TRADES`
WHERE `MT4_TRADES`.`LOGIN` = 2021400 AND `MT4_TRADES`.`CMD` IN (0, 1) AND `MT4_TRADES`.`CLOSE_TIME` >= '1970-01-01 00:00:00.1' AND `MT4_TRADES`.`CLOSE_TIME` < '2018-10-26 09:47:00.0'