zoukankan      html  css  js  c++  java
  • sqlalchemy 多线程 创建session

    1、基于threding.local,推荐使用

    from sqlalchemy.orm import sessionmaker
    from sqlalchemy import create_engine
    from sqlalchemy.orm import scoped_session
    from models import Student
    from threading import Thread
    
    engine = create_engine(
            "mysql+pymysql://root:密码@127.0.0.1:3306/数据库?charset=utf8",
            max_overflow=0,  # 超过连接池大小外最多创建的连接
            pool_size=5,  # 连接池大小
            pool_timeout=30,  # 池中没有线程最多等待的时间,否则报错
            pool_recycle=-1  # 多久之后对线程池中的线程进行一次连接的回收(重置)
        )
    SessionFactory = sessionmaker(bind=engine)
    session = scoped_session(SessionFactory)
    
    
    def task():
        ret = session.query(Student).all()
        # 将连接交还给连接池
        session.remove()
    
    
    
    for i in range(20):
        t = Thread(target=task)
        t.start()

    2、基于多线程

    from sqlalchemy.orm import sessionmaker
    from sqlalchemy import create_engine
    from models import Student
    from threading import Thread
    
    engine = create_engine(
            "mysql+pymysql://root:密码@127.0.0.1:3306/数据库?charset=utf8",
            max_overflow=0,  # 超过连接池大小外最多创建的连接
            pool_size=5,  # 连接池大小
            pool_timeout=30,  # 池中没有线程最多等待的时间,否则报错
            pool_recycle=-1  # 多久之后对线程池中的线程进行一次连接的回收(重置)
        )
    SessionFactory = sessionmaker(bind=engine)
    
    def task():
        # 去连接池中获取一个连接
        session = SessionFactory()
        ret = session.query(Student).all()
        # 将连接交还给连接池
        session.close()
    
    
    
    for i in range(20):
        t = Thread(target=task)
        t.start()
  • 相关阅读:
    nginx模块学习——nginx_http_push_module模块深入讲解和聊天室实现
    常见的qq在线客服代码
    MongoDB数据库介绍及安装(一)
    Python 创建类
    Python backup脚本
    Python 类的初始化小案例
    Python 类实例化
    Python 类初始化__init__
    ObjC(ObjectiveC): NSString应该用initWithFormat? 还是 stringWithFormat?
    NSUserDefaults
  • 原文地址:https://www.cnblogs.com/wt7018/p/11617864.html
Copyright © 2011-2022 走看看