Home  >  Article  >  Backend Development  >  How to Execute Raw SQL Queries in Flask-SQLAlchemy?

How to Execute Raw SQL Queries in Flask-SQLAlchemy?

Linda Hamilton
Linda HamiltonOriginal
2024-10-25 10:27:02848browse

How to Execute Raw SQL Queries in Flask-SQLAlchemy?

Executing Raw SQL in Flask-SQLAlchemy

To execute raw SQL in a Flask-SQLAlchemy application, you can utilize the built-in connection and engine objects provided by SQLAlchemy.

SQLAlchemy 2.0 and Later:

with engine.connect() as connection:
    result = connection.execute(text('SELECT * FROM your_table'))
    # Process the result...

SQLAlchemy 1.x (Deprecated):

from sqlalchemy import text

sql = text('SELECT name FROM penguins')
result = db.engine.execute(sql)
penguin_names = [row[0] for row in result]

In the 1.x example, db.engine.execute() executes the SQL query without using a connection, which is marked as deprecated in SQLAlchemy 2.0. To maintain backward compatibility and utilize the recommended connection-based approach in SQLAlchemy 2.0, you can employ the newer engine.connect() method.

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