zoukankan      html  css  js  c++  java
  • 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)
    
  • 相关阅读:
    WebService之使用CXF偶遇的BUG
    修改Web项目的名称后,在TomCat中部署项目,项目的名称还是与原来相同的解决方案
    JAVA面试题一 之 io流的操作
    第四天 字符串的格式化输出
    第三天 while循环 及其用法
    第二天 注释 、运算符,文件扩展名
    第一天 python入门 基础 “”“Hello World”和if-elif的使用、数据类型
    62. (待补)统计一个字符在字符串中出现次数 与 统计一个字符串在另一字符串中出现次数。
    61. 解析linux密码配置文件,获取配置文件信息,每行归纳为一个指针数组存入内存, 练习文件,数组,指针,字符串处理相关的配合使用要点
    60. 去字符串中的空格,去左空格,去右空格,去全部空格。
  • 原文地址:https://www.cnblogs.com/skymyyang/p/7808525.html
Copyright © 2011-2022 走看看