import sqlalchemy from sqlalchemy import create_engine from sqlalchemy.ext.declarative import declarative_base '''Column导入''' from sqlalchemy import Column, String, Integer, DATE,ForeignKey '''导入游标''' from sqlalchemy.orm import sessionmaker,relationship engine =create_engine("mysql+pymysql://xiaopang:521521@192.168.50.129/oldboydb", encoding='utf-8') #可以加echo=True显示数据 '''生成orm基类''' Base =declarative_base() class Student(Base): __tablename__ = 'student' # 表名 id = Column(Integer, primary_key=True) name =Column(String(32),nullable=False) register_date = Column(DATE, nullable=False) def __repr__(self): return "< %s name:%s >" % (self.id,self.name) class StudyRecord(Base): __tablename__ = "study_record" id = Column(Integer, primary_key=True) day =Column(Integer,nullable=False) status = Column(String(32),nullable=False) stu_id =Column(Integer,ForeignKey("student.id")) student = relationship("Student", backref="my_study_record") def __repr__(self): return "< %s day:%s status:%s>" % (self.student.name,self.day,self.status) Base.metadata.create_all(engine) # 创建表结构 Session_class=sessionmaker(bind=engine) Session=Session_class() # 生成session实例相当于cursor游标 '''多表插入数据''' # s1 =Student(name="goupang",register_date="2018-06-01") # s2 =Student(name="siwanyi",register_date="2018-06-02") # s3 =Student(name="yaosini",register_date="2018-06-03") # s4 =Student(name="xiaopang",register_date="2018-06-04") # study_obj1=StudyRecord(day=1,status="Yes",stu_id=1) # study_obj2=StudyRecord(day=2,status="No",stu_id=1) # study_obj3=StudyRecord(day=3,status="Yes",stu_id=1) # study_obj4=StudyRecord(day=1,status="Yes",stu_id=2) #Session.add_all([study_obj1,study_obj2,study_obj3,study_obj4]) '''多表查询''' stu_obj=Session.query(Student).filter().first() #调用my_study_record就是StudyRecord里面的所有属性(所有字段的数据) print(stu_obj.my_study_record) Session.commit()#提交
思路及过程:两个表互相取数据,通过ralationship关系连接,写到内存中