sqlalchemy : executing raw sql with parameter bindings

Max L. picture Max L. · Apr 21, 2014 · Viewed 35k times · Source

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

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)

Answer

alecxe picture alecxe · Apr 21, 2014

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

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.