Files
2026-09-19 15:00:19 +08:00

68 lines
2.8 KiB
Python

from sqlalchemy import *
from sqlalchemy.orm import declarative_base,sessionmaker
from datetime import datetime
db_url = "mysql+pymysql://root:123456@127.0.0.1:3306/ai0824?charset=utf8mb4"
engine = create_engine(db_url # 连接地址
,pool_size=50 # 连接池,同时可以保持50个已经创建好的数据库连接,放在池子里缓存使用
,echo=True
)
Base = declarative_base()
class Order(Base): # python里的表名字
__tablename__ = 'order_info_detail' # 实际数据库的表名字
id = Column( Integer # 声明字段的数据类型
, primary_key=True # 声明是主键
, autoincrement=True # 声明是自增主键
, comment='订单编号,自增主键' # 注释
)
title = Column( String(50) # 对应数据库的varchar类型
,nullable=False # 不允许为null
)
acc = Column(Integer)
userid = Column( Integer,ForeignKey('user_info_detail.id'),nullable=False ) # 外键约束
create_date = Column(DATETIME
, default=datetime.now # 默认值是当前时间
)
update_date = Column(DATETIME
, default=datetime.now # 首次创建的时间跟更新时间一致
, onupdate=datetime.now
)
class User(Base): # python里的表名字
__tablename__ = 'user_info_detail' # 实际数据库的表名字
id = Column(Integer # 声明字段的数据类型
, primary_key=True # 声明是主键
, autoincrement=True # 声明是自增主键
, comment='用户编号,自增主键' # 注释
)
usernmae = Column(String(50) # 对应数据库的varchar类型
, nullable=False # 不允许为null
, comment='用户名'
)
create_date = Column(DATETIME
, default=datetime.now # 默认值是当前时间
)
update_date = Column(DATETIME
, default=datetime.now # 首次创建的时间跟更新时间一致
, onupdate=datetime.now
)
Base.metadata.create_all(engine)
# User.__table__.create(engine,checkfirst = True)
u1 = User(usernmae='清华')
session = sessionmaker(bind=engine
,autoflush=False
,autocommit=False
)
db = session()
db.add(u1)
db.commit()
db.close()
n = 4 # 页数
m = 2 # 每页数据量
r6 = db.query(User).offset((n-1)*m).limit(m).all()
for i in r6:
print('分页:', i.id, i.usernmae)