# @ Time : 2021/1/31
# @ Author : ecithy
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String, Float
from sqlalchemy.orm import sessionmaker
from sqlalchemy import func
import random
# localhost
HOSTNAME = '127.0.0.1'
DATABASE = 'demo'
PORT = 3306
USERNAME = 'root'
PASSWORD = 'root'
DB_URL = 'mysql+mysqlconnector://{}:{}@{}:{}/{}?charset=utf8'.format(USERNAME, PASSWORD, HOSTNAME, PORT, DATABASE)
engine = create_engine(DB_URL)
Base = declarative_base(engine)
class Article(Base):
__tablename__ = 'article1'
id = Column(Integer, primary_key=True)
title = Column(String(50), nullable=False)
price = Column(Float, nullable=False)
# def __repr__(self):
def __str__(self):
return "Article(title:{},price:{})".format(self.title, self.price)
Base.metadata.create_all()
Session = sessionmaker(bind=engine)
session = Session()
# for i in range(6):
# article = Article(title="title%s" % i, price=random.randint(1, 50))
# session.add(article)
#
# session.commit()
# articles = session.query(Article).all()
# print(articles)
# for article in articles:
# print(article.title)
"""
func.count:统计行的数量。
func.avg:求平均值。
func.max:求最大值。
func.min:求最小值。
func.sum:求和。
"""
# 聚合函数
result = session.query(func.count(Article.id)).first()
print(result)
# result = session.query(func.avg(Article.price)).first()
# print(result)
# result = session.query(func.max(Article.price)).first()
# print(result)
result = session.query(func.sum(Article.price)).first()
print(result)