How to Execute Raw SQL in Flask-SQLAlchemy?

Barbara Streisand
Release: 2024-10-26 03:06:03
Original
830 people have browsed it

How to Execute Raw SQL in Flask-SQLAlchemy?

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

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

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!

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!