#coding=utf-8from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
USER ='xx'
PWD ='xx'
HOST ='127.0.0.1'
PORT =3306
DATA_BASE ='flask_db'
DB_URL =f'mysql+pymysql://{USER}:{PWD}@{HOST}:{PORT}/{DATA_BASE}'# 创建一个引擎
engine = create_engine(DB_URL)
Base = declarative_base(engine)
Session = sessionmaker(engine)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
main.py:
from turtle import title
from db_utils import Base,Session
from sqlalchemy import Column,Integer,String,func
from random import randint
classItem(Base):
__tablename__ ='t_items'id= Column(Integer,primary_key=True,autoincrement=True)
title = Column(String(32))
price = Column(Integer)defadd_data():with Session()as s:for i inrange(10):
item = Item(title=f'产品:{i+1}',price=randint(1,100))
s.add(item)
s.commit()defquery_data():with Session()as s:
item = s.query(Item).all()for i in item:print(i.title,i.price)defquery_data1():with Session()as s:
item = s.query(Item.price).all()for i in item:print(i.price)defquery_data2():with Session()as s:# n = s.query(func.count(Item.id)).first()# n = s.query(func.max(Item.price)).first()# n = s.query(func.avg(Item.price)).first()
n = s.query(func.sum(Item.price)).first()print(n)if __name__ =='__main__':# Base.metadata.create_all()# add_data()
query_data2()