SQLAlchemy教程

SQLAlchemy 使用函数

本章讨论了 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())
从上面的代码中,将获取学生表中的行数。
使用 Employee 表和以下数据演示了一些内置的 SQL 函数-
ID 名称 标记
1 卡马尔 56
2 费尔南德斯 85
3 苏尼尔 62
4 巴斯卡 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())
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4