在 Python 中使用数据库连接池
1. 引言
2. 连接池概述
3. Python 连接池实现方法
3.1 自行编写连接池
import sqlite3from queue import Queueclass SQLiteConnectionPool:def __init__(self, max_connections=5):self._pool = Queue(max_connections)for _ in range(max_connections):conn = sqlite3.connect(':memory:') # 或者你自己的数据库文件self._pool.put(conn)def get_connection(self):# 从连接池中获取一个连接return self._pool.get()def return_connection(self, conn):# 使用完毕后归还连接self._pool.put(conn)def close_all(self):# 关闭池中所有连接while not self._pool.empty():conn = self._pool.get()conn.close()
3.2 使用 SQLAlchemy 创建连接池
from sqlalchemy import create_engine# 创建引擎并指定连接池大小engine = create_engine('sqlite:///:memory:', pool_size=5, max_overflow=10)# 使用 with 语句自动获取和释放连接with engine.connect() as connection:result = connection.execute("SELECT 1")print(result.fetchall())
create_engine() 是创建数据库引擎的函数,其中 pool_size 参数定义了连接池的大小(即最多有多少个连接同时存在),而 max_overflow 则规定了当连接池满了之后,允许额外创建的临时连接数量。 通过 with 语句管理连接,确保用完连接后自动释放。
4. 连接池的进阶使用
事务管理
with engine.connect() as connection:trans = connection.begin() # 开启事务try:connection.execute("INSERT INTO my_table (id, name) VALUES (1, 'Tiger')")connection.execute("INSERT INTO my_table (id, name) VALUES (2, 'Lion')")trans.commit() # 提交事务except:trans.rollback() # 回滚事务raise
ORM 模型
from sqlalchemy.ext.declarative import declarative_basefrom sqlalchemy import Column, Integer, StringBase = declarative_base()class Animal(Base):__tablename__ = 'animals'id = Column(Integer, primary_key=True)name = Column(String)# 创建表Base.metadata.create_all(engine)# 插入数据from sqlalchemy.orm import sessionmakerSession = sessionmaker(bind=engine)session = Session()new_animal = Animal(name='Tiger')session.add(new_animal)session.commit()
5. 总结
对编程、职场感兴趣的同学,大家可以联系我微信:golang404,拉你进入“程序员交流群”。
资料包含了《IDEA视频教程》、《最全python面试题库》、《最全项目实战源码及视频》及《毕业设计系统源码》,总量高达650GB。全部免费领取!全面满足各个阶段程序员的学习需求。