sqlalchemy使用mysql常量的语法

时间:2016-08-31 00:21:20

标签: python mysql sqlalchemy literals func

所以我试图用 SECOND 常量调用mysql函数 TIMEDATEDIFF 作为第一个参数,如此

    query = session.query(func.TIME(Log.IncidentDetection).label('detection'), func.TIMESTAMPDIFF(SECOND,Log.IncidentDetection, Log.IncidentClear).label("duration")).all()
    print(query)

我已经尝试过它作为一个字符串,我得到一个mysql / mariadb错误:

query = session.query(func.TIME(Log.IncidentDetection).label('detection'), func.TIMESTAMPDIFF("SECOND",Log.IncidentDetection, Log.IncidentClear).label("duration")).all()
print(query)

给我这个

sqlalchemy.exc.ProgrammingError: (mysql.connector.errors.ProgrammingError) 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ''SECOND', log.`IncidentDetection`, log.`IncidentClear`) AS duration 
FROM log' at line 1 [SQL: 'SELECT TIME(log.`IncidentDetection`) AS detection, TIMESTAMPDIFF(%(TIMESTAMPDIFF_1)s, log.`IncidentDetection`, log.`IncidentClear`) AS duration \nFROM log'] [parameters: {'TIMESTAMPDIFF_1': 'SECOND'}]

我确信这是一件简单的事情,某种逃避序列或我失踪的导入。我查看了sqlalchemy文档无济于事。

1 个答案:

答案 0 :(得分:1)

要让sqlalchemy将字符串完全解析为查询,我使用了_literal_as_text()函数

工作解决方案

from sqlalchemy.sql.expression import func, _literal_as_text
# ...
query = session.query(func.TIME(Log.IncidentDetection).label('detection'), func.TIMESTAMPDIFF(_literal_as_text("SECOND"),Log.IncidentDetection, Log.IncidentClear).label("duration")).all()
print(query)