ChuannBlog

SQLAlchemy

SQLAlchemy结构

借助SQLAlchemy执行原生SQL

import threading
from sqlalchemy import create_engine

engine = create_engine(
    "mysql+pymysql://root:@127.0.0.1:3306/db5?charset=utf8",
    max_overflow=0,  # 超过连接池大小外最多创建的连接
    pool_size=5,  # 连接池大小
    pool_timeout=30,  # 池中没有线程最多等待的时间,否则报错
    pool_recycle=-1  # 多久之后对线程池中的线程进行一次连接的回收(重置)
)

def task():
    conn = engine.raw_connection()
    cursor = conn.cursor()
    cursor.execute(
        "select * from t1"
    )
    result = cursor.fetchall()
    print(result)
    cursor.close()
    conn.close()

for i in range(20):
    t = threading.Thread(target=task, args=(i,))
    t.start()

ORM

表操作

记录操作

扩展

sqlalchemy_utils

pip install sqlalchemy_utils
from sqlalchemy_utils import ChoiceType


class Test(Base):
	type_choices = ((1, "北京"),(2, "上海"),(3, "广州"),(4, "深圳"))
	id = Column(Intger, primary_key=True, autoincrement=True)
	name = Column(String(32))
	type = Column(ChoiceType(type_choice, Intger()))
session = Session()
obj = Test(name="alex",type=1)
session.add(obj)
session.commit()

result = session.query(Test).first()
print(result.type)
print(result.type.value)