main
COT001\李旭光 2026-03-18 18:05:54 +08:00
parent 4ef0819c48
commit 9bf754273a
1 changed files with 13 additions and 44 deletions

View File

@ -2,65 +2,34 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
""" """
数据库操作模块 数据库操作模块
使用SQLite存储工单数据 - 企业级连接池方案 使用SQLite存储工单数据
""" """
import sqlite3 import sqlite3
import json import json
from datetime import datetime, timedelta from datetime import datetime, timedelta
from typing import Dict, List, Optional from typing import Dict, List, Optional
from contextlib import contextmanager
import threading
class Database: class Database:
"""数据库操作类 - 使用连接池""" """数据库操作类"""
_instance = None
_lock = threading.Lock()
def __new__(cls, db_path: str = "wrench.db"):
"""单例模式确保全局唯一数据库实例"""
if cls._instance is None:
with cls._lock:
if cls._instance is None:
cls._instance = super().__new__(cls)
return cls._instance
def __init__(self, db_path: str = "wrench.db"): def __init__(self, db_path: str = "wrench.db"):
"""初始化数据库连接池""" """
if hasattr(self, '_initialized'): 初始化数据库
return :param db_path: 数据库文件路径
"""
self.db_path = db_path self.db_path = db_path
self._conn = None
self._conn_lock = threading.Lock()
self._initialized = True
self._init_connection()
self.init_database() self.init_database()
def _init_connection(self):
"""初始化持久连接"""
self._conn = sqlite3.connect(
self.db_path,
timeout=30.0,
check_same_thread=False,
isolation_level=None # 自动提交模式
)
self._conn.row_factory = sqlite3.Row
self._conn.execute('PRAGMA journal_mode=WAL')
self._conn.execute('PRAGMA synchronous=NORMAL')
self._conn.execute('PRAGMA cache_size=-64000')
self._conn.execute('PRAGMA busy_timeout=30000')
@contextmanager
def get_connection(self): def get_connection(self):
"""获取数据库连接的上下文管理器""" """获取数据库连接"""
with self._conn_lock: conn = sqlite3.connect(self.db_path, timeout=30.0, check_same_thread=False)
try: conn.row_factory = sqlite3.Row
yield self._conn conn.execute('PRAGMA journal_mode=WAL')
except sqlite3.Error as e: conn.execute('PRAGMA synchronous=NORMAL')
print(f"[ERROR] 数据库错误: {e}") conn.execute('PRAGMA cache_size=-64000')
raise return conn
def init_database(self): def init_database(self):
"""初始化数据库表""" """初始化数据库表"""