SQLAlchemy 使用文本SQL基础教程文档
收录于 2023-04-20 00:10:05 · بالعربية · English · Español · हिंदीName · 日本語 · Русский язык · 中文繁體
SQLAlchemy 允许您只使用字符串,适用于 SQL 已知且不强烈需要语句支持动态特性的情况。 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')]