无法使用session.execute查询MySQL

时间:2017-01-13 13:03:24

标签: python mysql session flask-sqlalchemy

我正在使用flask sqlalchemy。但是,在命令行中调试时,我发现session.execute返回错误。

Stock ='SHELL'
>>> db.session.execute("SELECT * FROM KJ WHERE Stock LIKE %s",(Stock,))
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "/usr/local/lib/python3.4/dist-packages/sqlalchemy/orm/scoping.py", line 149, in do
        return getattr(self.registry(), name)(*args, **kwargs)
      File "/usr/local/lib/python3.4/dist-packages/sqlalchemy/orm/session.py", line 978, in execute
        clause, params or {})
      File "/usr/local/lib/python3.4/dist-packages/sqlalchemy/engine/base.py", line 720, in execute
        return meth(self, multiparams, params)
      File "/usr/local/lib/python3.4/dist-packages/sqlalchemy/sql/elements.py", line 317, in _execute_on_connection
        return connection._execute_clauseelement(self, multiparams, params)
      File "/usr/local/lib/python3.4/dist-packages/sqlalchemy/engine/base.py", line 793, in _execute_clauseelement
        keys = distilled_params[0].keys()
    AttributeError: 'tuple' object has no attribute 'keys'

如果我正在使用db.engine.execute,它可以正常运行而没有错误

db.engine.execute("SELECT * FROM KLSE WHERE Stock LIKE %s",(Stock,))

另外,如果我导入mysqldb,使用游标执行,它也可以正常工作。

curs.execute("SELECT * FROM KJ WHERE Stock LIKE %s",(Stock,))

我怀疑的问题是%s与session.execute的股票不匹配。我查看sqlalchemy文档,但不明白。

  

执行(子句,参数=无,映射器=无,绑定=无,** kw)¶   http://docs.sqlalchemy.org/en/latest/orm/session_api.html

1 个答案:

答案 0 :(得分:0)

来自文档:

使用SELECT execute的格式如下:

execute(clause, params=None, mapper=None, bind=None, **kw)

使用以下选项在文档中有一个示例解决方案:

result = session.execute(
        "SELECT * FROM user WHERE id=:param",
        {"param":5}
    )

如果您的数据库连接设置正确,请遵循文档,以下内容应该有效:

Stock ='SHELL'
db.engine.execute(text("SELECT * FROM KLSE WHERE Stock LIKE :param"),{"param":Stock})

您的想法是将查询提供给text()函数,该函数是execute()的有效参数。这样,您就可以执行任何本身不可用的SQL作为SQLalchemy函数。即子句参数接受可执行语句(SQLalchemy函数或其他可执行函数,arbritrary字符串必须与text()一起传递,参数以字典形式给出。