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

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

Patricia Arquette
Patricia Arquette原創
2024-10-25 09:52:02379瀏覽

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() 方法:

<code class="python">with engine.connect() as connection:
    result = connection.execute(text('SELECT * FROM your_table'))
    # Perform operations on the result</code>

SQLAlchemy 1.x

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

<code class="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>
請注意,db.engine.execute() 方法執行「無連線」查詢,這表示它不會建立資料庫會話。此方法在 SQLAlchemy 2.0 中已棄用,為了一致性和最佳實踐,應避免使用此方法。

以上是以下是一些標題選項,請記住問題格式並專注於核心問題: **選項 1(直接且簡潔):** * **如何在 Flask-SQLAlchemy 中執行原始 SQL 查詢? **選擇的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn