」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > 以下是一些標題選項,請記住問題格式並專注於核心問題: **選項 1(直接且簡潔):** * **如何在 Flask-SQLAlchemy 中執行原始 SQL 查詢? **選擇

以下是一些標題選項,請記住問題格式並專注於核心問題: **選項 1(直接且簡潔):** * **如何在 Flask-SQLAlchemy 中執行原始 SQL 查詢? **選擇

發佈於2024-11-04
瀏覽:771

Here are a few title options, keeping in mind the question format and focusing on the core issue:

**Option 1 (Direct and concise):**

* **How to Execute Raw SQL Queries in Flask-SQLAlchemy?** 

**Option 2 (Highlighting the  difference between 1.x and 2.0

在Flask-SQLAlchemy 中執行原始SQL

在使用Flask-SQLAlchemy 時,您可能會遇到需要執行原始SQL 的場景查詢。這些查詢可能涉及複雜的表連接或內聯視圖。問題中示範的使用connection.execute() 的初始方法可能會觸發網關錯誤。為了解決這個問題,讓我們來探索 SQLAlchemy 版本 1.x 和 2.0 中推薦的方法。

SQLAlchemy 2.0

要在SQLAlchemy 2.0 中執行原始SQL,您可以利用engine.connect() 方法:

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

透過利用engine.connect()上下文管理器,您可以確保連線建立並在退出上下文時自動關閉。

SQLAlchemy 1. x

在SQLAlchemy 1.x 中,您可以使用db.engine.execute() 方法結合text() 函式執行原始SQL:

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 中已棄用,為了一致性和最佳實踐,應避免使用此方法。

最新教學 更多>

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3