Sometimes, we want to execute raw SQL in Python Flask-SQLAlchemy app.
In this article, we’ll look at how to execute raw SQL in Python Flask-SQLAlchemy app.
How to execute raw SQL in Python Flask-SQLAlchemy app?
To execute raw SQL in Python Flask-SQLAlchemy app, we can call db.session.execute.
For instance, we write
result = db.session.execute('SELECT * FROM my_table WHERE my_column = :val', {'val': 5})
to call db.session.execute with a SQL string with the :val placeholder.
Then we set the value of val in the dictionary in the 2nd argument.
The selected results are returned.
Conclusion
To execute raw SQL in Python Flask-SQLAlchemy app, we can call db.session.execute.