Mysql-Sqlalchemy-多表操作

來源:互聯網
上載者:User

標籤:建立   gis   圖片   技術分享   bsp   enc   表操作   div   false   

import sqlalchemyfrom sqlalchemy import create_enginefrom sqlalchemy.ext.declarative import declarative_base‘‘‘Column匯入‘‘‘from sqlalchemy import Column, String, Integer, DATE,ForeignKey‘‘‘匯入遊標‘‘‘from sqlalchemy.orm import sessionmaker,relationshipengine =create_engine("mysql+pymysql://xiaopang:[email protected]/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關係串連,寫到記憶體中

 

Mysql-Sqlalchemy-多表操作

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.