SQLAlchemy で生の SQL を実行するにはどうすればよいですか?
Flask 上で実行され、SQLAlchemy を介してデータベースとインターフェースする Python Web アプリがあります。
生の SQL を実行する方法が必要です。クエリには、インライン ビューとともに複数のテーブル結合が含まれます。
私はもう試した:
connection = db.session.connection()
connection.execute( <sql here> )
しかし、ゲートウェイ エラーが発生し続けます。
ベストアンサー1
SQLAlchemy 2.0:
with engine.connect() as connection:
result = connection.execute(text('SELECT * FROM your_table'))
# do something with the result..
SQLAlchemy 1.x:
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()
は「コネクションレス」であることに注意しましょう。SQLAlchemy 2.0 では非推奨。