- SQLAlchemy 教程
- SQLAlchemy - 首页
- SQLAlchemy - 简介
- SQLAlchemy 核心
- 表达式语言
- 连接数据库
- 创建表
- SQL表达式
- 执行表达式
- 选择行
- 使用文本SQL
- 使用别名
- 使用UPDATE表达式
- 使用DELETE表达式
- 使用多个表
- 使用多个表更新
- 参数有序更新
- 多个表删除
- 使用连接
- 使用连接词
- 使用函数
- 使用集合操作
- SQLAlchemy ORM
- 声明映射
- 创建会话
- 添加对象
- 使用Query
- 更新对象
- 应用过滤器
- 过滤器操作符
- 返回列表和标量
- 文本SQL
- 构建关系
- 处理相关对象
- 使用连接
- 常用关系运算符
- 提前加载
- 删除相关对象
- 多对多关系
- 方言
- SQLAlchemy有用资源
- SQLAlchemy - 快速指南
- SQLAlchemy - 有用资源
- 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())
从上面的代码中,将获取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())
广告