1. # @ Time : 2021/1/31
    2. # @ Author : ecithy
    3. from sqlalchemy import create_engine
    4. from sqlalchemy.ext.declarative import declarative_base
    5. from sqlalchemy import Column, Integer, String, Float
    6. from sqlalchemy.orm import sessionmaker
    7. from sqlalchemy import func
    8. import random
    9. # localhost
    10. HOSTNAME = '127.0.0.1'
    11. DATABASE = 'demo'
    12. PORT = 3306
    13. USERNAME = 'root'
    14. PASSWORD = 'root'
    15. DB_URL = 'mysql+mysqlconnector://{}:{}@{}:{}/{}?charset=utf8'.format(USERNAME, PASSWORD, HOSTNAME, PORT, DATABASE)
    16. engine = create_engine(DB_URL)
    17. Base = declarative_base(engine)
    18. class Article(Base):
    19. __tablename__ = 'article1'
    20. id = Column(Integer, primary_key=True)
    21. title = Column(String(50), nullable=False)
    22. price = Column(Float, nullable=False)
    23. # def __repr__(self):
    24. def __str__(self):
    25. return "Article(title:{},price:{})".format(self.title, self.price)
    26. Base.metadata.create_all()
    27. Session = sessionmaker(bind=engine)
    28. session = Session()
    29. # for i in range(6):
    30. # article = Article(title="title%s" % i, price=random.randint(1, 50))
    31. # session.add(article)
    32. #
    33. # session.commit()
    34. # articles = session.query(Article).all()
    35. # print(articles)
    36. # for article in articles:
    37. # print(article.title)
    38. """
    39. func.count:统计行的数量。
    40. func.avg:求平均值。
    41. func.max:求最大值。
    42. func.min:求最小值。
    43. func.sum:求和。
    44. """
    45. # 聚合函数
    46. result = session.query(func.count(Article.id)).first()
    47. print(result)
    48. # result = session.query(func.avg(Article.price)).first()
    49. # print(result)
    50. # result = session.query(func.max(Article.price)).first()
    51. # print(result)
    52. result = session.query(func.sum(Article.price)).first()
    53. print(result)