• 关联查询 join的使用


     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()
  • 相关阅读:
    爬虫学习笔记(二)http请求详解
    学习自动化的正确姿势
    binascii模块
    python一些内置函数及方法
    C小点,随便记记
    C:<conio.h>
    C,动态数组
    php intval()函数漏洞,is_numeric() 漏洞,绕过回文判断
    Mp3stego使用,附题,实验吧misc-Canon
    原生js实现Ajax
  • 原文地址:https://www.cnblogs.com/shiluoliming/p/6601017.html
Copyright © 2020-2023  润新知