Home  >  Article  >  Backend Development  >  How to Execute Raw SQL Queries in Flask-SQLAlchemy: A Guide for Versions 1.x and 2.0

How to Execute Raw SQL Queries in Flask-SQLAlchemy: A Guide for Versions 1.x and 2.0

Patricia Arquette
Patricia ArquetteOriginal
2024-10-25 23:02:29961browse

How to Execute Raw SQL Queries in Flask-SQLAlchemy: A Guide for Versions 1.x and 2.0

Executing Raw SQL in Flask-SQLAlchemy

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.

SQLAlchemy 2.0

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>

SQLAlchemy 1.x

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn