📜  SQLAlchemy核心-使用函数

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


本章讨论了SQLAlchemy中使用的一些重要功能。

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

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

类似地,将通过以下代码呈现将返回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())