Python3-sqlalchemy-orm 联表查询-无外键关系
#-*-coding:utf-8-*- #__author__ = "logan.xu" import sqlalchemy from sqlalchemy import create_engine,func from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import Column,Integer,String,DATE from sqlalchemy.orm import sessionmaker engine=create_engine("mysql+pymysql://root:12345678@localhost/news",encoding='utf-8',echo=True) Base=declarative_base() class User(Base): __tablename__='user' id=Column(Integer,primary_key=True) name=Column(String(32)) password=Column(String(64)) class Student(Base): __tablename__='student' id=Column(Integer,primary_key=True) name=Column(String(32),nullable=False) register_date=Column(DATE,nullable=False) gender=Column(String(32),nullable=False) def __repr__(self): return "<%s name:%s>" %(self.id,self.name) Base.metadata.create_all(engine) #创建表结构 Session_class=sessionmaker(bind=engine) #创建与数据库的会话session class,注意,这里返回给session的是这个class,不是实例 Session=Session_class() #生成session实例 #s1=Student(name="s2",register_date="2019-01-08",gender="F") s2=Student(name="s1",register_date="2019-01-09",gender="M") Session.add(s2) #联表查询两张表join-不带外键关系 print(Session.query(User,Student).filter(User.id==Student.id).all()) Session.commit() #现在才统一提交,创新数据