python sqlite3 线程池封装
import sqlite3
from concurrent.futures import ThreadPoolExecutor
class SQLiteThreadPoolExecutor:
def __init__(self, db_path, max_workers=10):
self.connection = sqlite3.connect(db_path, isolation_level=None)
self.cursor = self.connection.cursor()
self.max_workers = max_workers
self.executor = ThreadPoolExecutor(max_workers=max_workers)
def execute(self, query, parameters=()):
"""在线程池中执行SQL查询"""
future = self.executor.submit(self._execute, query, parameters)
return future
def _execute(self, query, parameters):
"""执行SQL查询"""
self.cursor.execute(query, parameters)
self.connection.commit()
return self.cursor.rowcount
def close(self):
"""关闭数据库连接和线程池"""
self.connection.close()
self.executor.shutdown(wait=True)
这个代码示例展示了如何使用concurrent.futures.ThreadPoolExecutor
来封装SQLite数据库操作,使其能够在多线程环境中执行。execute
方法接受SQL查询和参数,并返回一个Future
对象,可以用来异步获取执行结果。close
方法用于关闭数据库连接和线程池,确保所有资源得到释放。
评论已关闭