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

时间:2014-04-21 21:44:48

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

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

1 个答案:

答案 0 :(得分:43)

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