Integrating raw SQL within a Flask-SQLAlchemy web application presents a challenge due to the need to accommodate complex queries encompassing multiple table joins and inline views.
To address this, SQLAlchemy offers two approaches, one for version 2.0 and another for version 1.x.
Utilize the engine.connect() method to establish a connection with the database, allowing for raw SQL execution:
<code class="python">with engine.connect() as connection: result = connection.execute(text('SELECT * FROM your_table')) # Perform desired actions with the result</code>
Alternatively, consider the following approach:
<code class="python">from sqlalchemy import text sql = text('select name from penguins') result = db.engine.execute(sql) names = [row[0] for row in result] print(names)</code>
It's worth noting that db.engine.execute() is connectionless, which is regarded as deprecated in SQLAlchemy 2.0.
The above is the detailed content of How to Execute Raw SQL Queries in Flask-SQLAlchemy: A Guide for Versions 1.x and 2.0. For more information, please follow other related articles on the PHP Chinese website!