【问题标题】:sqlalchemy : executing raw sql with parameter bindingssqlalchemy : 使用参数绑定执行原始 sql
【发布时间】:2014-06-06 01:24:34
【问题描述】:

我正在尝试使用带有参数的 SQLALchemy(在 alembic 脚本中)运行这个简单的原始 sql 语句:

from alembic import op

t = {"code": "123", "description": "one two three"}

op.execute("insert into field_tags (id, field_id, code, description) "+
               "values (1,'zasz', :code ,:description')", t)

我收到以下错误:

sqlalchemy.exc.StatementError: A value is required for bind parameter 
  'description' (original cause: InvalidRequestError: A value is required for 
  bind parameter 'description') "insert into field_tags (id, field_id, code, 
  description) values (1, 'math', 
  %(code)s ,%(description)s)" []

解决办法:

t = {"code": "123", "description": "one two three"}
from sqlalchemy.sql import text

op.get_bind().execute(text("insert into field_tags (id, field_id, code, description) "+
               "values (1,'zasz', :code ,:description')"), **t)

【问题讨论】:

    标签: python sqlalchemy database-migration flask-sqlalchemy alembic


    【解决方案1】:

    您需要获取connection 对象,对其调用execute() 并将查询参数作为关键字参数传递:

    from alembic import op
    from sqlalchemy.sql import text
    
    conn = op.get_bind()
    conn.execute(
        text(
            """
                insert into field_tags 
                (id, field_id, code, description) 
                values 
                (1, 'zasz', :code , :description)
            """
        ), 
        **t
    )
    

    另见:How to execute raw SQL in SQLAlchemy-flask app

    【讨论】:

    • 我试过这个(传递 **t 作为参数)并得到:TypeError: execute() got an unexpected keyword argument 'code'
    • @MaxL.,我的错,你能试试更新答案中的代码吗?这个想法是获取连接对象并在其上调用execute()
    • 谢谢,这有帮助,我必须做出另一个改变:查询必须由文本函数(从 sqlalchemy.sql 导入文本)包装,给你的答案 +1,你添加 text() 包装,(就像我上面的更新一样)我会接受它作为最终答案。
    • 解决方案几乎是正确的。它仍然给出“得到一个意外的关键字参数”错误。把 '**t' 改成 't' 就可以了。
    • @AneilMallavarapu 请注意,Session 中的 execute(..)Connection 或 Engine 中的不同。
    猜你喜欢
    • 1970-01-01
    • 2023-03-18
    • 2018-11-15
    • 1970-01-01
    • 2018-09-28
    • 2023-03-26
    • 1970-01-01
    • 2018-09-08
    • 1970-01-01
    相关资源
    最近更新 更多