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')]
广告