Import sqlalchemyfrom sqlalchemy import create_enginefrom sqlalchemy.ext.declarative import declarative_base ' ' Column import ' from SQLAlchemy import Column, String, Integer, Date,foreignkey ' ' Import cursor ' from Sqlalchemy.orm import Sessionmaker,relationshipengine =create_engine ("Mysql+pymysql://xiaopang:[email protected]/oldboydb", encoding= ' Utf-8 ') #可以加echo =true display data ' Generate ORM base class ' Base =declarative_base () class Student (base): __tablename__ = ' Stu Dent ' # table name id = column (Integer, primary_key=true) name =column (String (+), 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 (+), Nullable=false) stu_id =column (Integer,foreignkey ("Student.id")) Student = Relationsh IP ("Student", backref= "My_study_record") deF __repr__ (self): return "<%s day:%s status:%s>"% (self.student.name,self.day,self.status) Base.metadata.cr Eate_all (engine) # CREATE TABLE Structure Session_class=sessionmaker (Bind=engine) Session=session_class () # Generate Session instance equivalent to cursor cursor ' Multiple table Insert Data ' ' # 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]) "Multiple table Query" "Stu_obj=session.query (Student). Filter ( ). First () #调用my_study_record就是StudyRecord里面的所有属性 (data for all fields) print (Stu_obj.my_study_record) session.commit () #提交
Thinking and process: Two tables fetch data from each other, connect via ralationship relationship, write into memory
mysql-sqlalchemy-Multi-table operation