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())

从上面的代码中,将获取students表中行数的计数。

使用包含以下数据的Employee表演示了一些内置的SQL函数:

ID 姓名 分数
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())

类似地,返回最小分数56的min()函数将通过以下代码呈现:

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())
广告
© . All rights reserved.