database
parent
4ef0819c48
commit
9bf754273a
|
|
@ -2,65 +2,34 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
数据库操作模块
|
||||
使用SQLite存储工单数据 - 企业级连接池方案
|
||||
使用SQLite存储工单数据
|
||||
"""
|
||||
|
||||
import sqlite3
|
||||
import json
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Dict, List, Optional
|
||||
from contextlib import contextmanager
|
||||
import threading
|
||||
|
||||
|
||||
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"):
|
||||
"""初始化数据库连接池"""
|
||||
if hasattr(self, '_initialized'):
|
||||
return
|
||||
"""
|
||||
初始化数据库
|
||||
:param db_path: 数据库文件路径
|
||||
"""
|
||||
self.db_path = db_path
|
||||
self._conn = None
|
||||
self._conn_lock = threading.Lock()
|
||||
self._initialized = True
|
||||
self._init_connection()
|
||||
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):
|
||||
"""获取数据库连接的上下文管理器"""
|
||||
with self._conn_lock:
|
||||
try:
|
||||
yield self._conn
|
||||
except sqlite3.Error as e:
|
||||
print(f"[ERROR] 数据库错误: {e}")
|
||||
raise
|
||||
"""获取数据库连接"""
|
||||
conn = sqlite3.connect(self.db_path, timeout=30.0, check_same_thread=False)
|
||||
conn.row_factory = sqlite3.Row
|
||||
conn.execute('PRAGMA journal_mode=WAL')
|
||||
conn.execute('PRAGMA synchronous=NORMAL')
|
||||
conn.execute('PRAGMA cache_size=-64000')
|
||||
return conn
|
||||
|
||||
def init_database(self):
|
||||
"""初始化数据库表"""
|
||||
|
|
|
|||
Loading…
Reference in New Issue