Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
443 views
in Technique[技术] by (71.8m points)

python - sqlalchemy : executing raw sql with parameter bindings

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)
question from:https://stackoverflow.com/questions/23206562/sqlalchemy-executing-raw-sql-with-parameter-bindings

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...