📜  SQLAlchemy核心-使用文本SQL

📅  最后修改于: 2020-11-27 07:35:25             🧑  作者: Mango


对于那些已经知道SQL并且不需要强烈支持动态功能的语句的情况,SQLAlchemy允许您仅使用字符串。 text()构造用于组成一个文本语句,该语句几乎不变地传递到数据库。

它构造一个新的TextClause ,直接表示文本SQL字符串,如下面的代码所示-

from sqlalchemy import text
t = text("SELECT * FROM students")
result = connection.execute(t)

与纯字符串相比, text()提供的优势是-

  • 对绑定参数的后端中立支持
  • 每个语句的执行选项
  • 结果栏输入行为

text()函数需要使用命名冒号格式的Bound参数。无论数据库后端如何,它们都是一致的。要发送参数值,我们将它们作为附加参数传递给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')]