来自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