SQLAlchemy Core - 使用函数

本章讨论了 SQLAlchemy 中使用的一些重要函数。

标准 SQL 推荐了许多由大多数方言实现的函数。它们根据传递给它的参数返回单个值。一些 SQL 函数将列作为参数,而一些是通用的。SQLAlchemy API 中的 func 关键字用于生成这些函数

在 SQL 中,now() 是一个通用函数。以下语句使用 func − 呈现 now() 函数

from sqlalchemy.sql import func
result = conn.execute(select([func.now()]))
print (result.fetchone())

上述代码的示例结果可能如下所示 −

(datetime.datetime(2018, 6, 16, 6, 4, 40),)

另一方面,count() 函数返回从表中选择的行数,通过使用 func 呈现 −

from sqlalchemy.sql import func
result = conn.execute(select([func.count(students.c.id)]))
print (result.fetchone())

从上面的代码中,将获取学生表中的行数。

使用以下数据的员工表演示了一些内置 SQL 函数−

ID Name Marks
1 Kamal 56
2 Fernandez 85
3 Sunil 62
4 Bhaskar 76

max() 函数通过以下方式实现,即使用 SQLAlchemy 中的 func,结果将为 85,即获得的总最高分数 −

from sqlalchemy.sql import func
result = conn.execute(select([func.max(employee.c.marks)]))
print (result.fetchone())

同样,min() 函数将返回最低分数 56,代码如下 −

from sqlalchemy.sql import func
result = conn.execute(select([func.min(employee.c.marks)]))
print (result.fetchone())

因此,AVG() 函数也可以通过使用以下代码实现 −

from sqlalchemy.sql import func
result = conn.execute(select([func.avg(employee.c.marks)]))
print (result.fetchone())

Functions are normally used in the columns clause of a select statement. 
They can also be given label as well as a type. A label to function allows the result 
to be targeted in a result row based on a string name, and a type is required when 
you need result-set processing to occur.from sqlalchemy.sql import func

result = conn.execute(select([func.max(students.c.lastname).label('Name')]))

print (result.fetchone())