importsqlalchemy
fromsqlalchemyimportcreate_engine#連接數(shù)據(jù)庫
fromsqlalchemy.ext.declarativeimportdeclarative_base#orm基類
fromsqlalchemyimportColumn,Integer,String,DATE,ForeignKey#Column列
fromsqlalchemy.ormimportsessionmaker,relationship
engine=create_engine("MySQL+pymysql://root:123456@192.168.0.6/wupeiqi",
encoding='utf-8',echo=False)#連接數(shù)據(jù)庫 echo=TRUE輸出執(zhí)行過程
base=declarative_base()# 生成基類
classStudent(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)
classStudyRecord(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'))#外鍵關(guān)聯(lián)到student的id
#StudyRecord通過student字段查詢Student表里所有數(shù)據(jù) 在內(nèi)存里建立relationship關(guān)系
student=relationship("Student",backref="my_study_record")#允許你可以在student表里通過my_study_record字段反查Studyrecord所有數(shù)據(jù)
def__repr__(self):
return"<%s day:%s status:%s>"%(self.student.name,self.day,self.status)
base.metadata.create_all(engine)#創(chuàng)建表
#連接mysql
Session_class = sessionmaker(bind=engine) # 創(chuàng)建與數(shù)據(jù)庫的連接session class ,注意,這里返回給session的是個(gè)class,不是實(shí)例
session = Session_class() # 生成session實(shí)例 session會(huì)話 類似cursor
'''
#插入數(shù)據(jù)
s1=Student(name="kobe",register_date="2017-05-16")
s2=Student(name="jack",register_date="2017-04-16")
s3=Student(name="duncon",register_date="2017-06-16")
s4=Student(name="Allen",register_date="2017-07-16")
record_1=StudyRecord(day=1,status="YES",stu_id=1)
record_2=StudyRecord(day=2,status="NO",stu_id=1)
record_3=StudyRecord(day=3,status="YES",stu_id=1)
record_4=StudyRecord(day=1,status="YES",stu_id=2)
session.add_all([s1,s2,s3,s4,record_1,record_2,record_3,record_4])
session.commit()
'''
#外鍵查詢數(shù)據(jù)
stu_obj=session.query(Student).filter(Student.name=="kobe").first()
print(stu_obj.my_study_record)
創(chuàng)新互聯(lián)建站主營獨(dú)山網(wǎng)站建設(shè)的網(wǎng)絡(luò)公司,主營網(wǎng)站建設(shè)方案,成都App定制開發(fā),獨(dú)山h5小程序開發(fā)搭建,獨(dú)山網(wǎng)站營銷推廣歡迎獨(dú)山等地區(qū)企業(yè)咨詢