python(12) : sqlserver数据库连接池

来自LLM 

连接池

# -*- coding: utf-8 -*-

# ====> 数据库连接池 <==== #

import traceback
from queue import Queue

import pymssql


class ConnectionPool:
    def __init__(self, server, user, password, database, max_connections):
        self.server = server
        self.user = user
        self.password = password
        self.database = database
        self.max_connections = max_connections
        self.connections = Queue(maxsize=max_connections)

        for _ in range(max_connections):
            conn = pymssql.connect(server, user, password, database, charset='cp936')
            print(f'初始化数据库连接池成功, 连接池数量{max_connections}')
            self.connections.put(conn)

    def get_connection(self):
        return self.connections.get()

    def release_connection(self, conn):
        self.connections.put(conn)

    def execute_query(self, query):
        conn = self.get_connection()
        result = None
        try:
            cursor = conn.cursor()
            cursor.execute(query)
            result = cursor.fetchall()
        except Exception as e:
            print(f'执行sql报错, msg:{e} sql:{query}')
            traceback.print_exc()
        self.release_connection(conn)
        return result


pool = ConnectionPool(
    '127.0.0.1:3433',
    'root',
    '123456',
    'mytest',
    5)
result = pool.execute_query('select * from t1')
print(result)

依赖

pip3 install pymssql -i https://mirrors.aliyun.com/pypi/simple/ requests

下面是一个使用Python创建SQL Server连接池的示例代码: ```python import pyodbc from queue import Queue from threading import Lock class SQLServerConnectionPool: def __init__(self, server, database, username, password, max_connections=5): self.server = server self.database = database self.username = username self.password = password self.max_connections = max_connections self.connection_queue = Queue(maxsize=max_connections) self.lock = Lock() self._create_connections(max_connections) def _create_connections(self, max_connections): for i in range(max_connections): connection = pyodbc.connect(f"Driver={{SQL Server}};Server={self.server};Database={self.database};UID={self.username};PWD={self.password}") self.connection_queue.put(connection) def get_connection(self): connection = self.connection_queue.get() return connection def release_connection(self, connection): self.connection_queue.put(connection) def close_all_connections(self): with self.lock: while not self.connection_queue.empty(): connection = self.connection_queue.get() connection.close() ``` 这个类的构造函数接收SQL Server的服务器名、数据库名、用户名和密码,以及最大连接数。它使用Python标准库中的队列(Queue)来存储连接,并使用锁(Lock)来确保线程安全。在初始化时,它创建max_connections个连接,并将它们放入队列中。当需要连接时,可以使用get_connection方法从队列中获取连接;使用release_connection方法将连接释放回队列中。最后,使用close_all_connections方法可以关闭所有连接并清空队列。 使用此类的示例代码: ```python pool = SQLServerConnectionPool(server='localhost', database='test', username='sa', password='password', max_connections=2) def query_database(): connection = pool.get_connection() cursor = connection.cursor() cursor.execute('SELECT * FROM test_table') rows = cursor.fetchall() pool.release_connection(connection) return rows for i in range(4): print(query_database()) pool.close_all_connections() ``` 在这个示例中,我们创建了一个连接池,最大连接数为2。我们定义了一个query_database函数,它从连接池中获取连接,执行SQL查询,然后释放连接。我们使用循环4次调用此函数,以测试连接池的行为。最后,我们使用close_all_connections方法关闭所有连接。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值