Home >Backend Development >Python Tutorial >How to Execute Raw SQL in Flask-SQLAlchemy?

How to Execute Raw SQL in Flask-SQLAlchemy?

Barbara Streisand
Barbara StreisandOriginal
2024-10-26 03:06:03985browse

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>

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!

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