SQLAlchemy ORM - 文字SQL



之前,已經從SQLAlchemy核心表示式語言的角度解釋了使用text()函式的文字SQL。現在我們將從ORM的角度來討論它。

透過使用text()結構指定其用法,可以在Query物件中靈活地使用字面字串。大多數適用方法都接受它。例如,filter()和order_by()。

在下面的示例中,filter()方法將字串“id<3”轉換為WHERE id<3

from sqlalchemy import text
for cust in session.query(Customers).filter(text("id<3")):
   print(cust.name)

生成的原始SQL表示式顯示了將filter轉換為帶有如下所示程式碼的WHERE子句:

SELECT customers.id 
AS customers_id, customers.name 
AS customers_name, customers.address 
AS customers_address, customers.email 
AS customers_email
FROM customers
WHERE id<3

從我們Customers表中的示例資料中,將選擇兩行,並列印name列,如下所示:

Ravi Kumar
Komal Pande

要使用基於字串的SQL指定繫結引數,請使用冒號,要指定值,請使用params()方法。

cust = session.query(Customers).filter(text("id = :value")).params(value = 1).one()

在Python控制檯中顯示的有效SQL如下所示:

SELECT customers.id 
AS customers_id, customers.name 
AS customers_name, customers.address 
AS customers_address, customers.email 
AS customers_email
FROM customers
WHERE id = ?

要使用完全基於字串的語句,可以將表示完整語句的text()結構傳遞給from_statement()。

session.query(Customers).from_statement(text("SELECT * FROM customers")).all()

上面程式碼的結果將是一個基本的SELECT語句,如下所示:

SELECT * FROM customers

顯然,將選擇customers表中的所有記錄。

text()結構允許我們將它的文字SQL與Core或ORM對映的列表達式按位置連結。我們可以透過將列表達式作為位置引數傳遞給TextClause.columns()方法來實現這一點。

stmt = text("SELECT name, id, name, address, email FROM customers")
stmt = stmt.columns(Customers.id, Customers.name)
session.query(Customers.id, Customers.name).from_statement(stmt).all()

將選擇所有行的id和name列,即使SQLite引擎執行上述程式碼生成的以下表達式顯示text()方法中的所有列:

SELECT name, id, name, address, email FROM customers
廣告
© . All rights reserved.