Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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) 
like image 412
Max L. Avatar asked Apr 21 '14 21:04

Max L.


People also ask

How do I run a raw SQL query in SQLAlchemy?

Import necessary functions from the SQLAlchemy package. Establish connection with the PostgreSQL database using create_engine() function as shown below, create a table called books with columns book_id and book_price. Insert record into the tables using insert() and values() function as shown.


1 Answers

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.

like image 171
alecxe Avatar answered Oct 03 '22 01:10

alecxe