- SQLAlchemy教程
- SQLAlchemy - 首頁
- SQLAlchemy - 簡介
- SQLAlchemy核心
- 表示式語言
- 連線資料庫
- 建立表
- SQL表示式
- 執行表示式
- 選擇行
- 使用文字SQL
- 使用別名
- 使用UPDATE表示式
- 使用DELETE表示式
- 使用多個表
- 使用多表更新
- 引數有序更新
- 多表刪除
- 使用連線
- 使用連線詞
- 使用函式
- 使用集合操作
- SQLAlchemy ORM
- 宣告對映
- 建立會話
- 新增物件
- 使用Query
- 更新物件
- 應用過濾器
- 過濾器運算子
- 返回列表和標量
- 文字SQL
- 構建關係
- 處理相關物件
- 處理連線
- 常用關係運算子
- 提前載入
- 刪除相關物件
- 多對多關係
- 方言
- SQLAlchemy有用資源
- SQLAlchemy - 快速指南
- SQLAlchemy - 有用資源
- SQLAlchemy - 討論
SQLAlchemy核心 - 使用文字SQL
對於那些SQL語句已知且不需要語句支援動態特性的情況,SQLAlchemy允許您直接使用字串。text()構造用於編寫一個文字語句,該語句幾乎不變地傳遞給資料庫。
它構造一個新的TextClause,直接表示文字SQL字串,如下面的程式碼所示:
from sqlalchemy import text
t = text("SELECT * FROM students")
result = connection.execute(t)
text()相對於普通字串的優勢在於:
- 對繫結引數的後端中立支援
- 每個語句的執行選項
- 結果列型別行為
text()函式需要以命名冒號格式的繫結引數。它們與資料庫後端無關。要傳送引數的值,我們將它們作為附加引數傳遞給execute()方法。
以下示例在文字SQL中使用繫結引數:
from sqlalchemy.sql import text
s = text("select students.name, students.lastname from students where students.name between :x and :y")
conn.execute(s, x = 'A', y = 'L').fetchall()
text()函式構造SQL表示式如下:
select students.name, students.lastname from students where students.name between ? and ?
x = 'A' 和 y = 'L' 的值作為引數傳遞。結果是一個包含'A'和'L'之間名稱的行列表:
[('Komal', 'Bhandari'), ('Abdul', 'Sattar')]
text()構造支援使用TextClause.bindparams()方法預先建立的繫結值。引數也可以顯式型別化如下:
stmt = text("SELECT * FROM students WHERE students.name BETWEEN :x AND :y")
stmt = stmt.bindparams(
bindparam("x", type_= String),
bindparam("y", type_= String)
)
result = conn.execute(stmt, {"x": "A", "y": "L"})
The text() function also be produces fragments of SQL within a select() object that
accepts text() objects as an arguments. The “geometry” of the statement is provided by
select() construct , and the textual content by text() construct. We can build a statement
without the need to refer to any pre-established Table metadata.
from sqlalchemy.sql import select
s = select([text("students.name, students.lastname from students")]).where(text("students.name between :x and :y"))
conn.execute(s, x = 'A', y = 'L').fetchall()
您還可以使用and_()函式組合使用text()函式建立的WHERE子句中的多個條件。
from sqlalchemy import and_
from sqlalchemy.sql import select
s = select([text("* from students")]) \
.where(
and_(
text("students.name between :x and :y"),
text("students.id>2")
)
)
conn.execute(s, x = 'A', y = 'L').fetchall()
上面的程式碼獲取名稱介於“A”和“L”之間且ID大於2的行。程式碼輸出如下:
[(3, 'Komal', 'Bhandari'), (4, 'Abdul', 'Sattar')]
廣告