from sqlalchemy.ext.declarative import declartive_base
from sqlalchemy import Column, String, Intgeger, create_engine
# 创建ORM模型基类
Base = declartive_base()
class User(Base):
__tablename__ = ‘user‘ # 数据库中表名
id = Column(Integer, primary_key=True, autoincrement=True)
name = Column(String(32), index=True)
# 创建引擎连接数据库
enginer = create_engine(‘mysql+pymysql://root:ruan@127.0.0.1:3306/tuan?charset=utf8‘)
# 创建所有继承Base类的数据表
Base.metadata.create_all()
# ------------------------------------------------------------------------------------------增------------------------------------------------------------------------------------------------------------
from sqlalchemy.orm import sessionmaker
# 创建会话窗口
Sesssion = sessionmaker(engine)
# 打开会话窗口
db_session = Session()
# 添加单条数据
res = db_session.add(User(name=‘ruan‘))
# 添加多条数据
“”“
res2 = db_session.add_all([
User(name=‘a‘),
User(name=‘b‘),
User(name=‘c‘),
])
“”“
# 提交数据
db_session.commit()
# 关闭会话窗口
db_session.close()
# ------------------------------------------------------------------------------------------删------------------------------------------------------------------------------------------------------------
from sqlalchemy.orm import sessionmaker
Session = sessionmaker()
db_session = Session()
res = db_session.query(User).filter(User.name==‘ruan‘).delete()
db_sesssion.commit()
db_session.close()
# ------------------------------------------------------------------------------------------改------------------------------------------------------------------------------------------------------------
res = db_sesssion.query(User).filter(User.name==‘ruan‘).uodate({name=‘sqlalchemy‘})
# ------------------------------------------------------------------------------------------查------------------------------------------------------------------------------------------------------------
res = db_session.query(User).filter(User.name==‘ruan‘).all()
res2 = db_session.query(User).filter_by(name=‘ruan‘).first()