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

Patricia Arquette
Release: 2024-10-25 23:02:29
Original
970 people have browsed it

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!