• Python sqlalchemy的基本使用


    示例代码

    from sqlalchemy import create_engine
    from sqlalchemy.ext.declarative import declarative_base
    from sqlalchemy import Integer, Column, String, DATE, Table, BigInteger
    
    #生成引擎
    engine = create_engine("mysql+pymysql://root:123456@localhost/mytest?charset=utf8")
    #常见ORM基类
    Base = declarative_base()
    
    #创建学生表
    class Student(Base):
        __tablename__ = 'student'
        id = Column(Integer, primary_key=True)
        name = Column(String(32))
        password = Column(String(64))
        mobile = Column(BigInteger)
        gradesclasses = Column(String(64))
        
    
    #创建老师表
    class Teacher(Base):
        __tablename__ = 'teacher'
        id = Column(Integer, primary_key=True)
        name = Column(String(32))
        password = Column(String(64))
        mobile = Column(BigInteger)
    
    if __name__ == "__main__":
        Base.metadata.create_all(engine)
    

    ORM多外键关联

    #ORM多外键关联
    
    from sqlalchemy import create_engine
    from sqlalchemy import Integer, ForeignKey, String, Column
    from sqlalchemy.ext.declarative import declarative_base
    from sqlalchemy.orm import relationship
    
    
    engine = create_engine("mysql+pymysql://skymyyang:666666@mfgskymyyang.chinacloudapp.cn/myyang",
                           encoding='utf-8')
    Base = declarative_base()
    
    
    class Customer(Base):
        __tablename__ = 'customer'
        id = Column(Integer, primary_key=True)
        name = Column(String(32))
    
        billing_address_id = Column(Integer, ForeignKey("address.id"))  #账单地址
        shipping_address_id = Column(Integer, ForeignKey("address.id")) #邮寄地址 这两个地址同时关联了 同一个地址表
    
        billing_address = relationship("Address", foreign_keys = [billing_address_id])
        shipping_address = relationship("Address", foreign_keys = [shipping_address_id])  #通过关联差address表
    
    
    class Address(Base):
        __tablename__ = 'address'
        id = Column(Integer, primary_key=True)
        street = Column(String(64))
        city = Column(String(64))
        state = Column(String(64))
        def __repr__(self):
            return self.street
    
    Base.metadata.create_all(engine) #创建表结构
    
    

    然后进行查询以及数据插入

    from daynine import orm_mang_fk
    
    from sqlalchemy.orm import session,sessionmaker
    
    Session_class = sessionmaker(bind=orm_mang_fk.engine)
    session = Session_class()#生成session实例 相当于cursor
    
    # addr1 = orm_mang_fk.Address(street="Tiantongyuan", city="Changping", state="BJ")
    # addr2 = orm_mang_fk.Address(street="Wudaokou", city="Haidian", state="BJ")
    # addr3 = orm_mang_fk.Address(street="Yanjiao", city="LangFang", state="HB")
    # session.add_all([addr1, addr2, addr3])
    # c1 = orm_mang_fk.Customer(name = "skymyyang", billing_address_id = 4, shipping_address_id = 5)
    # c2 = orm_mang_fk.Customer(name = "mayun",  billing_address_id = 6, shipping_address_id = 6)
    # session.add_all([c1, c2])
    # session.commit()
    obj = session.query(orm_mang_fk.Customer).filter(orm_mang_fk.Customer.name =="skymyyang").first()
    print(obj.name, obj.billing_address, obj.shipping_address)
    

    ORM多对多

    #ORM多对多
    
    from sqlalchemy import create_engine
    from sqlalchemy import Integer, ForeignKey, String, Column, DATE, Table
    from sqlalchemy.ext.declarative import declarative_base
    from sqlalchemy.orm import relationship
    #创建引擎
    engine = create_engine("mysql+pymysql://skymyyang:666666@mfgskymyyang.chinacloudapp.cn/myyang?charset=utf8",encoding='utf-8')
    #生成ORM基类
    Base = declarative_base()
    book_m2m_author = Table('book_m2m_author', Base.metadata,
                            Column('book_id', Integer, ForeignKey('books.id')),
                            Column('author_id', Integer, ForeignKey('authors.id')),
    )
    
    class Book(Base):
        __tablename__ = 'books'
        id = Column(Integer, primary_key=True)
        name = Column(String(64))
        pub_date = Column(DATE)
        authors = relationship('Author', secondary=book_m2m_author, backref = 'books')
    
        def __repr__(self):
            return self.name
    
    class Author(Base):
        __tablename__ = 'authors'
        id = Column(Integer, primary_key=True)
        name = Column(String(32))
        email = Column(String(64))
    
        def __repr__(self):
            return self.name
    
    
    if __name__  ==  '__main__':
        Base.metadata.create_all(engine)
    
  • 相关阅读:
    hdu 3715(二分+2-sat)
    hdu 3622(二分+2-sat判断可行性)
    hdu 3062+1824(2-sat入门)
    【转载】lucene中Field.Index,Field.Store详解
    【转载】那些年我们一起清除过的浮动demo
    【转载】那些年我们一起清除过的浮动
    【转载】Visaul Studio 常用快捷键的动画演示
    【转载】各浏览器CSS兼容问题
    【转载】HTTP 错误 500.19
    【转载】Memcached在.Net中的基本操作
  • 原文地址:https://www.cnblogs.com/skymyyang/p/7808525.html
Copyright © 2020-2023  润新知