1 #!/usr/bin/env python 2 import sqlalchemy 3 from sqlalchemy import create_engine 4 from sqlalchemy.ext.declarative import declarative_base 5 from sqlalchemy import Column, Integer, String,ForeignKey 6 from sqlalchemy.orm import sessionmaker,relationship 7 print(sqlalchemy.__version__) 8 9 engine = create_engine('mysql+pymysql://root:taochen123@127.0.0.1:3306/a1',echo = True) 10 11 Base = declarative_base(engine) 12 13 class Father(Base): 14 __tablename__ = "father" 15 16 id = Column(Integer,autoincrement=True,primary_key=True) 17 name = Column(String(20)) 18 son = relationship('Father') 19 def __repr__(self): 20 return self.name 21 22 class Son(Base): 23 __tablename__ = 'son' 24 id = Column(Integer,autoincrement=True,primary_key=True) 25 name = Column(String(20)) 26 email = Column(String(20)) 27 father_id = Column(Integer,ForeignKey('father.id')) 28 Base.metadata.create_all(engine) 29 30 Session = sessionmaker(bind=engine) 31 session = Session() 32 # f1 = Father(name = "fafafa") 33 # session.add(f1) 34 # s1 = Son(name = 'sq',email = '@qq.com',father_id = 1) 35 # s2 = Son(name = 'sw', email= 'q@qq.com',father_id= 1) 36 # session.add_all([s1,s2]) 37 38 39 ret = session.query(Father.name,Son.name).join(Son).first() 40 print("ret=",ret) 41 session.commit()