python使用单例模式创建MySQL链接

实际项目中,多个方法使用MySQL连接,若每次新建、关闭连接,高访问量时可能致服务器崩溃。单例模式可解决此问题,本文采用Python单例模式方法4,因其更pythonic,还给出了代码及使用方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在实际项目中,可能会在多个不同的方法中使用MySQL链接,如果每次都新建、关闭连接,当访问量高时可能会造服务器崩溃无法访问等问题,而单例模式可以很好的解决这个问题。

关于python的单例模式这篇文章有详细的例子,这里我们使用方法4,因为这种方法更加pythonic。

代码如下:

 

from functools import wraps
import mysql.connector
from sshtunnel import SSHTunnelForwarder


def singleton(cls):
    instances = {}

    @wraps(cls)
    def get_instance(*args, **kw):
        if cls not in instances:
            instances[cls] = cls(*args, **kw)
        return instances[cls]
    return get_instance


# 数据库连接实例
@singleton
class MySQLSingle(object):
    def __init__(self, conn='', server=''):
        self.conn = conn
        self.server = server

    def get_conn(self, host_jump, port_jump, ssh_pk_jump, user_name_jump, host_mysql, port_mysql, user_name_mysql, password_mysql, database):
        try:
            self.server = SSHTunnelForwarder(
                (host_jump, int(port_jump)),  # 跳板机的配置
                ssh_pkey=ssh_pk_jump,
                ssh_username=user_name_jump,
                remote_bind_address=(host_mysql, int(port_mysql)))  # 数据库服务器的配置
            self.server.start()
            self.conn = mysql.connector.connect(host='127.0.0.1', port=self.server.local_bind_port, user=user_name_mysql,
                                           password=password_mysql, database=database)
        except Exception as e:
            print('File to connect database: %s' % e)
        return self.conn, self.server

使用方法如下:

 

mysql_single = MySQLSingle()
conn, server = mysql_single.get_conn(host_jump, port_jump, ssh_pk_jump, user_name_jump, host_mysql, port_mysql,
                                     user_name_mysql, password_mysql, database)
# do something...
conn.close()
server.close()
### Python实现 MySQL 连接池的操作 在 Python 中,可以通过多种方式来实现 MySQL连接池功能。以下是基于 `DBUtils` 和 `torndb` 库的两种常见方法。 #### 方法一:使用 `DBUtils.PooledDB` 通过 `DBUtils.PooledDB` 可以轻松创建并管理 MySQL 数据库连接池。以下是一个完整的代码示例: ```python import pymysql from DBUtils.PooledDB import PooledDB # 创建连接池对象 pool = PooledDB( creator=pymysql, # 使用 pymysql 作为数据库驱动 maxconnections=6, # 最大连接数 mincached=2, # 初始化时至少缓存的连接数量 blocking=True, # 如果超过最大连接数,是否阻塞等待 ping=0, # 检查连接状态的时间间隔 (单位秒),0 表示不检查 host='localhost', # 主机地址 user='root', # 用户名 password='password', # 密码 database='test_db' # 数据库名称 ) def query_data(): conn = pool.connection() # 获取连接 cursor = conn.cursor() try: sql = "SELECT * FROM users" cursor.execute(sql) result = cursor.fetchall() return result finally: cursor.close() conn.close() if __name__ == "__main__": data = query_data() print(data) ``` 上述代码展示了如何配置和使用 `PooledDB` 来管理多个并发请求中的数据库连接[^1]。 --- #### 方法二:使用 `torndb` 实现连接池 另一种常见的做法是利用 `torndb` 提供的功能来简化连接池实现过程。需要注意的是,在某些版本中可能需要针对特定环境调整兼容性设置(如 Python 3.6 或更高版本)[^3]。 安装依赖项: ```bash pip install torndb ``` 下面是具体的实现代码: ```python import torndb class DatabasePool(object): _instance = None def __new__(cls, *args, **kwargs): if cls._instance is None: cls._instance = super(DatabasePool, cls).__new__(cls, *args, **kwargs) # 配置数据库参数 db_config = { 'host': 'localhost', 'database': 'test_db', 'user': 'root', 'password': 'password' } # 建立单例模式下的共享实例 cls.db_instance = torndb.Connection(**db_config) return cls._instance @staticmethod def get_connection(): return DatabasePool()._instance.db_instance def fetch_user_info(user_id): db_conn = DatabasePool.get_connection() sql = f"SELECT name, email FROM users WHERE id={user_id}" result = db_conn.query(sql) return result if __name__ == "__main__": info = fetch_user_info(1) print(info) ``` 此方案适用于 Tornado Web 框架或其他异步场景下更高效的资源分配需求。 --- 关于错误处理方面,如果遇到类似于 “MySQL server has gone away”的异常,则可能是由于长时间未活动导致连接被关闭所致。可以尝试增加超时时间或者定期发送心跳包保持活跃状态[^2]。 --- #### 性能优化建议 为了进一步提升性能与稳定性,可考虑以下几个方向: 1. 调整 `maxconnections` 参数至合理范围; 2. 设置合适的 `ping` 时间间隔检测闲置链接有效性; 3. 对于高负载应用引入 Redis 缓存机制减少直接查询次数; ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值