Thirty-two: The data in the database can be queried SQLAlchemy.query functions and aggregate functions

Ready to work

Import create_engine SQLAlchemy from, the Column, Integer, String, the Float 
from sqlalchemy.ext.declarative Import declarative_base
from sqlalchemy.orm Import sessionmaker

# database information
Host = '127.0.0.1'
Port = '3306'
Database = 'db_to_sqlalchemy'
username = 'the root '
password =' 123456 '

# + type database database connection plug, pymysql used herein
DB_URI = f'mysql pymysql +:} // {username: password} {Host} {@: {Port} / {database}'

Engine = create_engine (DB_URI) # creation engine
base = declarative_base (engine) # use declarative_base create a base class
the session = sessionmaker (engine) ()


class Article This article was (base):
__tablename__ = 'Article This article was'
ID = the Column (Integer, primary_key = True, AUTOINCREMENT = True)
title = Column(String(50), nullable=False)
price = Column(Float, nullable=Float)

def __repr__(self):
return f'Article(title): {self.title}、Article(price): {self.price}'


Base.metadata.create_all() # 创建数据库

# 造测试数据
import random

for x in range(6):
article = Article(title=f'title{x}', price=random.randint(1, 100))
session.add(article)
session.commit()

 

query data query function can be
1, the object model
2, model property to specify only the search for a model in which several properties
3, an aggregate function

 

1, the object model

 

2, the model attributes can be specified to find only a few of the properties of a model

 

3, aggregate functions, objects imported func

func source

_FunctionGenerator source

That sql statement aggregate functions can be used here

 

The number of rows of statistics: func.count

func.avg: Averaging

func.max: seeking maximum

func.min: for the minimum

func.sum: summing

 

Guess you like

Origin www.cnblogs.com/zhongyehai/p/11808512.html