由于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 保密
05-28 08:50