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:
JavaScript
x
3
1
connection = db.session.connection()
2
connection.execute( <sql here> )
3
But I keep getting gateway errors.
Advertisement
Answer
Have you tried:
JavaScript
1
2
1
result = db.engine.execute("<sql here>")
2
or:
JavaScript
1
7
1
from sqlalchemy import text
2
3
sql = text('select name from penguins')
4
result = db.engine.execute(sql)
5
names = [row[0] for row in result]
6
print names
7
Note that db.engine.execute()
is “connectionless”, which is deprecated in SQLAlchemy 2.0.