我正在尝试使用SQLAlchemy对某些原始SQL执行某些查询绑定(由于复杂性),但它似乎没有正确绑定命名参数。运行以下代码时出现错误,如果我手动编辑SQL字符串以使用设置值,则运行正常:
engine = create_engine('mysql://scott:tiger@localhost/foo')
vals = {
'tag_id': 1,
'interval': 300,
'start_time': datetime.datetime(2014, 5, 1, 0, 0),
'end_time': datetime.datetime(2014, 6, 1, 0, 0)
}
sql = """SELECT
FROM_UNIXTIME( CEIL( UNIX_TIMESTAMP( event_time ) / :interval ) * :interval ) AS pseudo_time,
AVG( value ) AS average_value
FROM `data_point_double`
WHERE
(tag_id = :tag_id) AND
(event_time BETWEEN :start_time AND :end_time)
GROUP BY CEIL( UNIX_TIMESTAMP( event_time ) / :interval ), tag_id"""
result = engine.execute(sql, **vals)
这会导致以下错误:
sqlalchemy.exc.ProgrammingError :( ProgrammingError)(1064,“您的SQL语法有错误;请查看与您的MySQL服务器版本对应的手册,以便在':interval附近使用正确的语法)*:interval) AS pseudo_time,...
日志似乎表明正在传递参数:
2014-05-26 23:23:55,506 INFO sqlalchemy.engine.base.Engine SELECT
FROM_UNIXTIME( CEIL( UNIX_TIMESTAMP( event_time ) / :interval ) * :interval ) AS pseudo_time,
AVG( value ) AS average_value
FROM `data_point_double`
WHERE
(tag_id = :tag_id) AND
(event_time BETWEEN :start_time AND :end_time)
GROUP BY CEIL( UNIX_TIMESTAMP( event_time ) / :interval ), tag_id
2014-05-26 23:23:55,506 INFO sqlalchemy.engine.base.Engine {'start_time': datetime.datetime(2014, 5, 1, 0, 0), 'interval': 300, 'end_time': datetime.datetime(2014, 6, 1, 0, 0), 'tag_id': 1L}
2014-05-26 23:23:55,506 INFO sqlalchemy.engine.base.Engine ROLLBACK
我是否正确使用了命名参数或这是一个更大的问题?我也试过mysql + mysqldb作为引擎,但这也不起作用。
答案 0 :(得分:0)
在发布之前我找到了解决方案,使用文本来包装查询,这样:
result = engine.execute(sql, **vals)
成为这个:
from sqlalchemy.sql import text
result = engine.execute(text(sql), **vals)
希望带有错误消息的内容可以帮助有人找到这个解决方案!