yj
2026-03-31 4becf7b5eba5de2d9889f379eb88aeb6cb16f760
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
import json
import pymysql
import logging
 
# 设置日志记录
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
 
 
class DatabaseConfig:
    def __init__(self, config_file="config.json"):
        """从JSON文件初始化数据库配置"""
        try:
            with open(config_file) as f:
                config = json.load(f)
        except FileNotFoundError:
            logger.error(f"配置文件 {config_file} 未找到")
            raise
        except json.JSONDecodeError:
            logger.error(f"配置文件 {config_file} 中JSON格式无效")
            raise
 
        if "database" not in config:
            logger.error("配置文件中未找到数据库配置")
            raise ValueError("数据库配置缺失")
 
        db_config = config["database"]
 
        self.host = db_config.get("host", "localhost")
        self.port = int(db_config.get("port", 3306))
        self.user = db_config.get("user", "root")
        self.password = db_config.get("password", "")
        self.database_name = db_config.get("database_name", "admin_db")
        self.charset = db_config.get("charset", "utf8mb4")
 
    def get_connection(self):
        """建立并返回MySQL数据库连接"""
        try:
            connection = pymysql.connect(
                host=self.host,
                port=self.port,
                user=self.user,
                password=self.password,
                database=self.database_name,
                charset=self.charset,
                cursorclass=pymysql.cursors.DictCursor,
            )
            return connection
        except Exception as e:
            logger.error(f"连接数据库时出错: {e}")
            return None
 
 
def init_database(config_file="config.json"):
    """初始化数据库和所需表"""
    try:
        with open(config_file) as f:
            config = json.load(f)
    except FileNotFoundError:
        logger.error(f"配置文件 {config_file} 未找到")
        raise
    except json.JSONDecodeError:
        logger.error(f"配置文件 {config_file} 中JSON格式无效")
        raise
 
    if "database" not in config:
        logger.error("配置文件中未找到数据库配置")
        raise ValueError("数据库配置缺失")
 
    db_config = config["database"]
 
    # 不指定数据库连接以创建数据库(如果需要)
    try:
        connection = pymysql.connect(
            host=db_config.get("host", "localhost"),
            port=int(db_config.get("port", 3306)),
            user=db_config.get("user", "root"),
            password=db_config.get("password", ""),
            charset=db_config.get("charset", "utf8mb4"),
        )
    except Exception as e:
        logger.error(f"建立初始数据库连接时出错: {e}")
        raise
 
    try:
        with connection.cursor() as cursor:
            # 如果数据库不存在则创建
            cursor.execute(
                f"CREATE DATABASE IF NOT EXISTS {db_config.get('database_name', 'admin_db')}"
            )
            connection.commit()
 
            # 选择数据库
            cursor.execute(f"USE {db_config.get('database_name', 'admin_db')}")
 
            # 创建ContentType表 - 包含id、code、name字段
            create_contenttype_table_sql = """
            CREATE TABLE IF NOT EXISTS content_type (
                id INT AUTO_INCREMENT PRIMARY KEY,
                code VARCHAR(50) NOT NULL UNIQUE,
                name VARCHAR(255) NOT NULL,
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
                INDEX idx_code (code)
            )
            """
            cursor.execute(create_contenttype_table_sql)
 
            # 创建Content表 - 包含id、Type(外键)、Question、Answer字段
            create_content_table_sql = """
            CREATE TABLE IF NOT EXISTS content (
                id INT AUTO_INCREMENT PRIMARY KEY,
                type_id INT NOT NULL,
                question TEXT NOT NULL,
                answer TEXT NOT NULL,
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
                FOREIGN KEY (type_id) REFERENCES content_type(id) ON DELETE CASCADE,
                INDEX idx_type (type_id)
            )
            """
            cursor.execute(create_content_table_sql)
 
            connection.commit()
 
            logger.info("数据库和表初始化成功!")
    except Exception as e:
        logger.error(f"初始化数据库时出错: {e}")
        raise
    finally:
        connection.close()