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