Search code examples
pythonsqlsqlalchemyflaskflask-sqlalchemy

How to execute raw SQL in Flask-SQLAlchemy app


How do you execute raw SQL in SQLAlchemy?

I have a python web app that runs on flask and interfaces to the database through SQLAlchemy.

I need a way to run the raw SQL. The query involves multiple table joins along with Inline views.

I've tried:

connection = db.session.connection()
connection.execute( <sql here> )

But I keep getting gateway errors.


Solution

  • SQLAlchemy 2.0:

    with engine.connect() as connection:
        result = connection.execute(text('SELECT * FROM your_table'))
        # do something with the result..
    

    SQLAlchemy 1.x:

    from sqlalchemy import text
    
    sql = text('select name from penguins')
    result = db.engine.execute(sql)
    names = [row[0] for row in result]
    print names
    

    Note that db.engine.execute() is "connectionless", which is deprecated in SQLAlchemy 2.0.