Commit 42cd7484 by zhouhaibao

fix(database): 修复数据库连接验证逻辑

- 将数据库创建逻辑替换为连接验证逻辑
- 移除自动创建数据库的功能
- 添加数据库连接测试查询
- 更新成功和失败的日志消息
- 添加异常处理和错误抛出机制
1 parent 6901d710
......@@ -468,7 +468,7 @@ if hasattr(DataProcessor, 'init_app'):
def ensure_database():
"""MySQL:自动创建数据库(若不存在)。SQLite 无需处理。"""
"""检查数据库连接是否正常。数据库已由 DBA 预先创建,此处仅做连通性验证。"""
uri = app.config['SQLALCHEMY_DATABASE_URI']
if not uri.startswith('mysql'):
return
......@@ -476,21 +476,19 @@ def ensure_database():
from urllib.parse import urlsplit, unquote
p = urlsplit(uri)
dbname = p.path.lstrip('/')
conn = pymysql.connect(
host=p.hostname, port=p.port or 3306,
user=unquote(p.username or 'root'), password=unquote(p.password or ''),
charset='utf8mb4', connect_timeout=5,
)
try:
conn = pymysql.connect(
host=p.hostname, port=p.port or 3306,
user=unquote(p.username or 'root'), password=unquote(p.password or ''),
charset='utf8mb4', connect_timeout=5,
)
with conn.cursor() as cur:
cur.execute(
f"CREATE DATABASE IF NOT EXISTS `{dbname}` DEFAULT CHARACTER SET utf8mb4 "
"COLLATE utf8mb4_unicode_ci"
)
conn.commit()
finally:
cur.execute("SELECT 1")
conn.close()
print(f'[MySQL] 数据库就绪: {dbname}')
print(f'[MySQL] 数据库连接成功: {dbname}')
except Exception as e:
print(f'[MySQL] 数据库连接失败: {e}')
raise
def init_default_user():
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!