How to Execute Raw SQL Queries in Flask-SQLAlchemy?

Linda Hamilton
Release: 2024-10-25 10:27:02
Original
856 people have browsed it

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

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

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!

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!