Home >Backend Development >Python Tutorial >How to Execute Raw SQL Queries in Flask-SQLAlchemy?
Executing Raw SQL in Flask-SQLAlchemy
To execute raw SQL in a Flask-SQLAlchemy application, you can utilize the built-in connection and engine objects provided by SQLAlchemy.
SQLAlchemy 2.0 and Later:
with engine.connect() as connection: result = connection.execute(text('SELECT * FROM your_table')) # Process the result...
SQLAlchemy 1.x (Deprecated):
from sqlalchemy import text sql = text('SELECT name FROM penguins') result = db.engine.execute(sql) penguin_names = [row[0] for row in result]
In the 1.x example, db.engine.execute() executes the SQL query without using a connection, which is marked as deprecated in SQLAlchemy 2.0. To maintain backward compatibility and utilize the recommended connection-based approach in SQLAlchemy 2.0, you can employ the newer engine.connect() method.
The above is the detailed content of How to Execute Raw SQL Queries in Flask-SQLAlchemy?. For more information, please follow other related articles on the PHP Chinese website!