Home >Database >Mysql Tutorial >How Can I 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>
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>
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!