Home > Database > Mysql Tutorial > How Can I Execute Raw SQL Queries in Flask-SQLAlchemy?

How Can I Execute Raw SQL Queries in Flask-SQLAlchemy?

Susan Sarandon
Release: 2025-01-17 05:21:09
Original
569 people have browsed it

How Can I Execute Raw SQL Queries in Flask-SQLAlchemy?

Execute raw SQL queries in Flask-SQLAlchemy

Django applications can use from django.db import connection to execute raw SQL queries, but this method is not available in the Flask-SQLAlchemy environment.

In Flask-SQLAlchemy, you can execute raw SQL queries using SQLAlchemy's engine.execute() method. Here’s how to do it:

SQLAlchemy 2.0:

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

SQLAlchemy 1.x:

<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

Note:

In SQLAlchemy 2.0, db.engine.execute() has been deprecated in favor of the connectionless engine.connect() method.

The above is the detailed content of How Can I Execute Raw SQL Queries 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