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')]
廣告
© . All rights reserved.