Executing Raw SQL in Flask-SQLAlchemy
When working with complex database queries, it may become necessary to execute raw SQL directly within Flask-SQLAlchemy applications. There are a few methods to achieve this, depending on the SQLAlchemy version in use.
SQLAlchemy 2.0
Utilizing the higher-level APIs introduced in version 2.0, raw SQL can be executed through the 'engine' object:
<code class="python">with engine.connect() as connection: result = connection.execute(text('SELECT * FROM your_table')) # Process the result as needed...</code>
SQLAlchemy 1.x
For versions 1.x, raw SQL execution is performed using the 'engine.execute()' method:
<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>
Note that 'db.engine.execute()' is considered "connectionless" in SQLAlchemy 2.0 and is deprecated. Therefore, it is recommended to follow the SQLAlchemy 2.0 approach when using the latest versions of the framework.
The above is the detailed content of How to Execute Raw SQL in Flask-SQLAlchemy?. For more information, please follow other related articles on the PHP Chinese website!