Python sqlalchemy:使用参数绑定执行原始 sql

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23206562/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 02:29:45  来源:igfitidea点击:

sqlalchemy : executing raw sql with parameter bindings

pythonsqlalchemydatabase-migrationflask-sqlalchemyalembic

提问by Max L.

I'm trying to run this simple raw sql statement with parameters with SQLALchemy (within an alembic script) :

我正在尝试使用 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)

And I get the following error :

我收到以下错误:

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)" []


The solution:

解决方案:

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)

采纳答案by alecxe

You need to get the connectionobject, call execute()on it and pass query parameters as keyword arguments:

您需要获取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
)

Also see: How to execute raw SQL in SQLAlchemy-flask app.

另请参阅:如何在 SQLAlchemy-flask 应用程序中执行原始 SQL