python,编写一个最简单的数据库连接池程序
时间: 2024-12-11 21:43:58 浏览: 1
Python实现一个简单的MySQL类
在Python中,可以使用第三方库如`psycopg2`(针对PostgreSQL)或`pymysql`(针对MySQL)结合`contextlib`和`concurrent.futures`模块来实现一个基础的数据库连接池。这里我以`sqlite3`为例,因为它是Python内置的数据库模块,更易于展示:
```python
from contextlib import contextmanager
import sqlite3
from concurrent.futures import ThreadPoolExecutor
class ConnectionPool:
def __init__(self, max_connections=5):
self.pool = []
self.max_connections = max_connections
for _ in range(max_connections):
self.pool.append(self.create_connection())
@staticmethod
def create_connection():
conn = sqlite3.connect('test.db')
conn.row_factory = sqlite3.Row
return conn
def get_connection(self):
if not self.pool:
return self.create_connection()
with self.pool.pop() as conn:
yield conn
def release_connection(self, conn):
# 在with语句结束后自动释放资源
conn.close()
if len(self.pool) < self.max_connections:
self.pool.append(conn)
@contextmanager
def connection_pool():
pool = ConnectionPool()
try:
yield from pool.get_connection()
finally:
pool.release_connection(conn)
# 使用示例
with connection_pool() as conn:
cursor = conn.cursor()
cursor.execute("SELECT * FROM table_name")
rows = cursor.fetchall()
print(rows)
```
这个简单的数据库连接池会在每次需要数据库连接时从连接池中获取,并在操作完成后自动归还。如果连接池已满,则会创建新的连接。
阅读全文