如何在 SQLAlchemy 中执行原始 SQL?
我有一个 Python Web 应用程序,它在 flask 上运行并通过 SQLAlchemy 连接到数据库。
我需要一种方法来运行原始 SQL。该查询涉及多个表连接以及内联 View 。
我试过了:
connection = db.session.connection()
connection.execute( <sql here> )
但我不断收到网关错误。
最佳答案
你试过了吗:
result = db.engine.execute("<sql here>")
或:
from sqlalchemy import text
sql = text('select name from penguins')
result = db.engine.execute(sql)
names = [row[0] for row in result]
print names
请注意,db.engine.execute()
是“无连接”,即 deprecated in SQLAlchemy 2.0 .
https://stackoverflow.com/questions/17972020/