替换连接池
This commit is contained in:
		@@ -1,27 +1,47 @@
 | 
			
		||||
import pymysql
 | 
			
		||||
from configs.config import MYSQL_HOST, MYSQL_PORT, MYSQL_NAME, MYSQL_USER, MYSQL_PASS
 | 
			
		||||
from dbutils.pooled_db import PooledDB
 | 
			
		||||
 | 
			
		||||
# 创建 MySQL 连接
 | 
			
		||||
def create_connection():
 | 
			
		||||
    return pymysql.connect(
 | 
			
		||||
        host=MYSQL_HOST,
 | 
			
		||||
        user=MYSQL_USER,
 | 
			
		||||
        port=MYSQL_PORT,  # 应该使用 MYSQL_PORT 而不是 MYSQL_HOST
 | 
			
		||||
        password=MYSQL_PASS,
 | 
			
		||||
        database=MYSQL_NAME,
 | 
			
		||||
        local_infile=True,
 | 
			
		||||
        cursorclass=pymysql.cursors.DictCursor
 | 
			
		||||
    )
 | 
			
		||||
 | 
			
		||||
# 连接 MySQL (开启 MySQL 服务)
 | 
			
		||||
conn = create_connection()
 | 
			
		||||
# 创建数据库连接池
 | 
			
		||||
pool = PooledDB(
 | 
			
		||||
    creator=pymysql,        # 使用 pymysql 作为数据库驱动
 | 
			
		||||
    maxconnections=20,      # 最大连接数
 | 
			
		||||
    mincached=2,            # 初始化时,连接池中至少创建的空闲连接
 | 
			
		||||
    maxcached=5,            # 连接池中最多空闲连接数
 | 
			
		||||
    blocking=True,          # 超过最大连接数时,是否阻塞
 | 
			
		||||
    maxusage=None,          # 单个连接的最大复用次数
 | 
			
		||||
    ping=0,                 # 设置连接是否检查
 | 
			
		||||
    host=MYSQL_HOST,
 | 
			
		||||
    port=MYSQL_PORT,
 | 
			
		||||
    user=MYSQL_USER,
 | 
			
		||||
    password=MYSQL_PASS,
 | 
			
		||||
    database=MYSQL_NAME,
 | 
			
		||||
    charset='utf8mb4'
 | 
			
		||||
)
 | 
			
		||||
 | 
			
		||||
# 获取 MySQL 连接
 | 
			
		||||
def get_cursor():
 | 
			
		||||
    global conn
 | 
			
		||||
    try:
 | 
			
		||||
        conn.ping()
 | 
			
		||||
        return conn.cursor()
 | 
			
		||||
    except Exception:
 | 
			
		||||
        conn = create_connection()
 | 
			
		||||
        return conn.cursor()
 | 
			
		||||
## 创建 MySQL 连接
 | 
			
		||||
#def create_connection():
 | 
			
		||||
#    return pymysql.connect(
 | 
			
		||||
#        host=MYSQL_HOST,
 | 
			
		||||
#        user=MYSQL_USER,
 | 
			
		||||
#        port=MYSQL_PORT,  # 应该使用 MYSQL_PORT 而不是 MYSQL_HOST
 | 
			
		||||
#        password=MYSQL_PASS,
 | 
			
		||||
#        database=MYSQL_NAME,
 | 
			
		||||
#        local_infile=True,
 | 
			
		||||
#        cursorclass=pymysql.cursors.DictCursor
 | 
			
		||||
#    )
 | 
			
		||||
#
 | 
			
		||||
## 连接 MySQL (开启 MySQL 服务)
 | 
			
		||||
#conn = create_connection()
 | 
			
		||||
#
 | 
			
		||||
## 获取 MySQL 连接
 | 
			
		||||
#def get_cursor():
 | 
			
		||||
#    global conn
 | 
			
		||||
#    try:
 | 
			
		||||
#        conn.ping()
 | 
			
		||||
#        return conn.cursor()
 | 
			
		||||
#    except Exception:
 | 
			
		||||
#        conn = create_connection()
 | 
			
		||||
#        return conn.cursor()
 | 
			
		||||
#
 | 
			
		||||
		Reference in New Issue
	
	Block a user