标签:com init string 需要 class als odi user pre
#!/usr/bin/env python # -*- coding:utf-8 -*- from sqlalchemy import create_engine from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import Column, Integer, String, Boolean from sqlalchemy import ForeignKey from sqlalchemy.orm import relationship from sqlalchemy.orm import sessionmaker engine = create_engine("mysql+pymysql://root:redhat@192.168.10.209/db01?charset=utf8") Base = declarative_base() class Student(Base): __tablename__ = ‘student‘ id = Column(Integer, primary_key=True) name = Column(String(32), nullable=False) address = relationship(‘Address‘, backref=‘student‘) class Address(Base): __tablename__ = ‘address‘ id = Column(Integer, primary_key=True) u_id = Column(Integer, ForeignKey(‘student.id‘)) name = Column(String(32), nullable=False) # Base.metadata.drop_all(bind=engine) Base.metadata.create_all(bind=engine) session_cls = sessionmaker(bind=engine) session = session_cls() session.add_all([ Student(name=‘user1‘), Student(name=‘user2‘), Student(name=‘user3‘), Address(u_id=1, name=‘add-1‘), Address(u_id=2, name=‘add-2‘), Address(u_id=3, name=‘add-3‘), Address(u_id=3, name=‘add-4‘), ]) # session.commit() # 利用 backref查找,成功 ret = session.query(Address).filter(Address.u_id == 1).first().student.name print(ret)
#!/usr/bin/env python # -*- coding:utf-8 -*- import random from sqlalchemy.ext.automap import automap_base from sqlalchemy.orm import Session from sqlalchemy.orm import relationship from sqlalchemy import create_engine # 初始化一个automap类 Base = automap_base() engine = create_engine("mysql+pymysql://root:redhat@192.168.10.209/db01?charset=utf8") Base.prepare(engine, reflect=True) # 反射所有的表 session = Session(engine) Student = Base.classes.student # 获取所需要的表 Address = Base.classes.address
# 利用表的backref 成功获取结果 ret = session.query(Address).filter(Address.u_id == 1).first().student.name print(ret)
标签:com init string 需要 class als odi user pre
原文地址:http://www.cnblogs.com/qiaogy/p/6295672.html