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.