• SQLAlchemy-Utils


    由于sqlalchemy中没有提供choice方法,所以借助SQLAlchemy-Utils组件提供的choice方法。

    安装:

    pip3 install sqlalchemy_utils

    示例:

    from sqlalchemy.ext.declarative import declarative_base
    from sqlalchemy import Column
    from sqlalchemy import Integer, String
    from sqlalchemy import create_engine
    from sqlalchemy_utils import ChoiceType
    
    Base = declarative_base()
    
    
    class UserInfo(Base):
        __tablename__ = "userinfo"
    
        id = Column(Integer, primary_key=True)
        name = Column(String(16), index=True, unique=True, nullable=False, autoincrement=True)
        gender_choices = (
            (0, ""),
            (1, ""),
            (2, "保密")
        )
        gender = Column(ChoiceType(gender_choices, Integer()))
    
        __table_args__ = {
            "mysql_engine": "Innodb",
            "mysql_charset": "utf8",
        }
    
    
    def init_db():
        """根据类创建数据库表"""
        engine = create_engine(
            "mysql+pymysql://root:""@127.0.0.1:3306/sqlalchemy_db?charset=utf8",
            max_overflow=0,  # 超过连接池大小外最多创建的连接
            pool_size=5,     # 连接池大小
            pool_timeout=20, # 池中没有连接最多等待的时间,否则报错
            pool_recycle=-1  # 多久之后对线程池中的线程进行一次连接的回收(重置)
        )
        Base.metadata.create_all(engine)
    
    
    def drop_db():
        """根据类删除数据库表"""
        engine = create_engine(
            "mysql+pymysql://root:""@127.0.0.1:3306/sqlalchemy_db?charset=utf8",
            max_overflow=0,
            pool_size=5,
            pool_timeout=20,
            pool_recycle=-1
        )
        Base.metadata.drop_all(engine)
    
    
    if __name__ == "__main__":
        drop_db()
        init_db()
    models.py
    from models import UserInfo
    from sqlalchemy import create_engine
    from sqlalchemy.orm import sessionmaker
    
    engine = create_engine(
        "mysql+pymysql://root:""@127.0.0.1:3306/sqlalchemy_db?charset=utf8",
        max_overflow=0,  # 超过连接池大小外最多创建的连接
        pool_size=5,     # 连接池大小
        pool_timeout=20, # 池中没有连接最多等待的时间,否则报错
        pool_recycle=-1  # 多久之后对线程池中的线程进行一次连接的回收(重置)
    )
    SessionFactory = sessionmaker(bind=engine)
    session = SessionFactory()
    
    ret = session.query(UserInfo).all()
    for row in ret:
        print(row.id, row.name, row.gender.value)
    # 1 pd 男
    # 2 pq 保密
    View Code
  • 相关阅读:
    Sampling Distribution of the Sample Mean|Central Limit Theorem
    OS L2-3: Process Creation and Operations
    c++函数重载、内联函数、类、友元
    命名空间及异常处理
    C++继承与多态,代码复用之泛型和模板
    ORB_GMS图像对齐
    ORB对齐
    [转]OpenCV中ORB特征点检测和匹配简单用法
    [转]OpenCV学习笔记】之鼠标的调用
    [转]OpenCV—Mat类
  • 原文地址:https://www.cnblogs.com/believepd/p/10372269.html
Copyright © 2020-2023  润新知