60

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)

1 Answer 1

88

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.

Sign up to request clarification or add additional context in comments.

5 Comments

I tried this (passing **t as argument) and got : TypeError: execute() got an unexpected keyword argument 'code'
@MaxL., my bad, could you try the code from the updated answer? The idea is to get the connection object and call execute() on it.
Thanks, that helped, there was another change I had to make : the query must be wrapped by the text function (from sqlalchemy.sql import text), gave a +1 to your answer, it you add the text() wrapp, (like in my update above) I'll accept it as the definitive answer.
The solution is almost correct. It still gives a 'got an unexpected keyword argument' error. Change '**t' to 't', and it works.
@AneilMallavarapu Note that execute(..) from Session is different from the one in Connection or Engine.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.