Home > Database > Mysql Tutorial > How to Execute Raw SQL Statements in Flask-SQLAlchemy?

How to Execute Raw SQL Statements in Flask-SQLAlchemy?

Linda Hamilton
Release: 2025-01-17 05:16:09
Original
775 people have browsed it

How to Execute Raw SQL Statements in Flask-SQLAlchemy?

Execute raw SQL statements in Flask-SQLAlchemy

In Flask-SQLAlchemy applications, when processing complex queries involving table joins and inline views, it is often necessary to execute raw SQL statements. SQLAlchemy provides several methods for this, depending on the version used.

SQLAlchemy 2.0

With SQLAlchemy 2.0, raw SQL can be executed through the engine.connect() context manager as follows:

<code class="language-python">with engine.connect() as connection:
    result = connection.execute(text('SELECT * FROM your_table'))
    # 对结果对象进行操作...</code>
Copy after login

SQLAlchemy 1.x

In SQLAlchemy 1.x, raw SQL execution requires the text module as follows:

<code class="language-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 should be noted that db.engine.execute() in SQLAlchemy 1.x does not establish a connection when executing statements, which has been deprecated in SQLAlchemy 2.0.

The above is the detailed content of How to Execute Raw SQL Statements 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