时间:2021-07-01 10:21:17 帮助过:15人阅读
2.创建外键关联的表结构:
from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() from sqlalchemy import Column,Integer,String,ForeignKey from sqlalchemy.orm import relationship class Student(Base): __tablename__ = "student" id = Column(Integer,primary_key=True) name = Column(String(32),nullable=False) sch_id = Column(Integer,ForeignKey("school.id")) # 关联的表的字段,表间的关系 stu2sch = relationship("School",backref="sch2stu") # 写在哪边那边就是正向查询,对象间的关系,backref(反向查询) class School(Base): __tablename__ = "school" id = Column(Integer,primary_key=True) name = Column(String(32),nullable=False) from sqlalchemy import create_engine engine = create_engine("mysql+pymysql://root:@127.0.0.1:3306/SQLAlchemy_Pro?charset=utf8") Base.metadata.create_all(engine)
3、单表数据的增删改查:
from sqlalchemy.orm import sessionmaker from sqlalchemy import create_engine from creatTable import Users # 创建引擎 engine = create_engine("mysql+pymysql://root:@127.0.0.1:3306/SQLAlchemy_Pro?charset=utf8") Session = sessionmaker(engine) db_session = Session() # 1. 增加数据add(创建表结构的类名(字段名=添加的数据)) db_session.add(Users(name="ZWQ")) # 相当于建立一条添加数据的sql语句 db_session.commit() # 执行 db_session.close() # 结束关闭 # 批量添加 db_session.add_all([Users(name="清风徐来"), Users(name="水波不兴")]) db_session.commit() db_session.close() # 2.查询 query(表结构的类名) sqlres = db_session.query(Users) print(sqlres) # 直接翻译输出对应的SQL查询语句 res = db_session.query(Users).all() # 返回表中所有数据对象 print(res)# [<creatTable.Users object at 0x00000000038A1B00>,<creatTable.Users object at 0x00000000038A1B70>] for u in res: print(u.id, u.name) res = db_session.query(Users).first() # 取第一个,返回是对象 print(res.id, res.name) res = db_session.query(Users).filter(Users.id == 3).first() # 返回符合条件查询结果 print(res.name) res = db_session.query(Users).filter(Users.id <= 2, Users.name == "ZWQ").all() # filter中的条件可以是模糊条件,多个条件 for u in res: print(u.id,u.name) # 3.更改数据 update({k:v}) res = db_session.query(Users).filter(Users.id == 1).update({"name":"DragonFire"}) print(res) db_session.commit() res = db_session.query(Users).update({"name":"ZWQ"}) # 全部修改,返回修改的数据个数 print(res) db_session.commit() # 4.删除 delete()结合查询条件删除 res = db_session.query(Users).filter(Users.id == 1).delete() # 删除否合条件的数据,返回删除数量 print(res) db_session.commit() res = db_session.query(Users).delete() # 删除表中所有数据,返回删除数量 print(res) db_session.commit()
SQLAlchemy
标签:als bsp imp _id 条件查询 data ack 自动 sql查询语句