models.py
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column
from sqlalchemy import Integer,String,Text,Date,DateTime
from sqlalchemy import create_engine
Base = declarative_base()
class Users(Base):
__tablename__ = ‘users‘
id = Column(Integer, primary_key=True)
name = Column(String(32), index=True, nullable=False)
def create_all():
engine = create_engine(
"mysql+pymysql://root:[email protected]:3306/s9day120?charset=utf8",
max_overflow=0, # 超过连接池大小外最多创建的连接
pool_size=5, # 连接池大小
pool_timeout=30, # 池中没有线程最多等待的时间,否则报错
pool_recycle=-1 # 多久之后对线程池中的线程进行一次连接的回收(重置)
)
Base.metadata.create_all(engine)
def drop_all():
engine = create_engine(
"mysql+pymysql://root:[email protected]:3306/s9day120?charset=utf8",
max_overflow=0, # 超过连接池大小外最多创建的连接
pool_size=5, # 连接池大小
pool_timeout=30, # 池中没有线程最多等待的时间,否则报错
pool_recycle=-1 # 多久之后对线程池中的线程进行一次连接的回收(重置)
)
Base.metadata.drop_all(engine)
if __name__ == ‘__main__‘:
create_all()
views.py
from sqlalchemy.orm import sessionmaker
from sqlalchemy import create_engine
from models import Users
# 创建引擎
engine = create_engine(
"mysql+pymysql://root:[email protected]:3306/s9day120?charset=utf8",
max_overflow=0, # 超过连接池大小外最多创建的连接
pool_size=5, # 连接池大小
pool_timeout=30, # 池中没有线程最多等待的时间,否则报错
pool_recycle=-1 # 多久之后对线程池中的线程进行一次连接的回收(重置)
)
# 根据引擎创建session工厂
SessionFactory = sessionmaker(bind=engine)
# 用session工厂创建一个session对象
session = SessionFactory()
..........
# 根据Users类对users表进行增删改查
..........
# 关闭session
session.close()
操作
增
obj = Users(name=‘alex‘)
session.add(obj)
session.commit()
session.add_all([
Users(name=‘小东北‘),
Users(name=‘龙泰‘)
])
session.commit()
删
session.query(Users).filter(Users.id >= 2).delete()
session.commit()
改
session.query(Users).filter(Users.id == 4).update({Users.name:‘东北‘})
session.query(Users).filter(Users.id == 4).update({‘name‘:‘小东北‘})
session.query(Users).filter(Users.id == 4).update({‘name‘:Users.name+"DSB"},synchronize_session=False)
session.commit()
查
result = session.query(Users).all()
for row in result:
print(row.id,row.name)
result = session.query(Users).filter(Users.id >= 2)
for row in result:
print(row.id,row.name)
result = session.query(Users).filter(Users.id >= 2).first()
print(result)