95 lines
2.9 KiB
Python
95 lines
2.9 KiB
Python
|
|
"""
|
|||
|
|
使用 Python 执行数据库初始化脚本
|
|||
|
|
"""
|
|||
|
|
import pymysql
|
|||
|
|
import sys
|
|||
|
|
from pathlib import Path
|
|||
|
|
|
|||
|
|
# 数据库配置
|
|||
|
|
DB_CONFIG = {
|
|||
|
|
'host': '10.100.51.51',
|
|||
|
|
'port': 3306,
|
|||
|
|
'user': 'root',
|
|||
|
|
'password': 'Unis@123',
|
|||
|
|
'charset': 'utf8mb4',
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
def execute_sql_file(sql_file_path):
|
|||
|
|
"""执行 SQL 文件"""
|
|||
|
|
try:
|
|||
|
|
# 读取 SQL 文件
|
|||
|
|
with open(sql_file_path, 'r', encoding='utf-8') as f:
|
|||
|
|
sql_content = f.read()
|
|||
|
|
|
|||
|
|
# 连接数据库
|
|||
|
|
print("正在连接数据库...")
|
|||
|
|
connection = pymysql.connect(**DB_CONFIG)
|
|||
|
|
|
|||
|
|
try:
|
|||
|
|
with connection.cursor() as cursor:
|
|||
|
|
# 分割SQL语句(简单分割,按分号)
|
|||
|
|
statements = []
|
|||
|
|
current_statement = []
|
|||
|
|
|
|||
|
|
for line in sql_content.split('\n'):
|
|||
|
|
# 跳过注释
|
|||
|
|
line = line.strip()
|
|||
|
|
if line.startswith('--') or not line:
|
|||
|
|
continue
|
|||
|
|
|
|||
|
|
current_statement.append(line)
|
|||
|
|
|
|||
|
|
# 如果行以分号结尾,表示一条完整的语句
|
|||
|
|
if line.endswith(';'):
|
|||
|
|
statement = ' '.join(current_statement)
|
|||
|
|
if statement.strip():
|
|||
|
|
statements.append(statement)
|
|||
|
|
current_statement = []
|
|||
|
|
|
|||
|
|
# 执行所有语句
|
|||
|
|
print(f"共 {len(statements)} 条SQL语句...")
|
|||
|
|
for i, statement in enumerate(statements, 1):
|
|||
|
|
try:
|
|||
|
|
cursor.execute(statement)
|
|||
|
|
# 如果是SELECT语句,获取结果
|
|||
|
|
if statement.strip().upper().startswith('SELECT'):
|
|||
|
|
result = cursor.fetchall()
|
|||
|
|
if result:
|
|||
|
|
print(f" [{i}] {result}")
|
|||
|
|
else:
|
|||
|
|
print(f" [{i}] 执行成功")
|
|||
|
|
except Exception as e:
|
|||
|
|
print(f" [{i}] 执行失败: {e}")
|
|||
|
|
print(f" SQL: {statement[:100]}...")
|
|||
|
|
|
|||
|
|
# 提交事务
|
|||
|
|
connection.commit()
|
|||
|
|
print("\n✅ 数据库初始化完成!")
|
|||
|
|
|
|||
|
|
finally:
|
|||
|
|
connection.close()
|
|||
|
|
|
|||
|
|
except FileNotFoundError:
|
|||
|
|
print(f"❌ SQL 文件不存在: {sql_file_path}")
|
|||
|
|
sys.exit(1)
|
|||
|
|
except pymysql.Error as e:
|
|||
|
|
print(f"❌ 数据库错误: {e}")
|
|||
|
|
sys.exit(1)
|
|||
|
|
except Exception as e:
|
|||
|
|
print(f"❌ 未知错误: {e}")
|
|||
|
|
sys.exit(1)
|
|||
|
|
|
|||
|
|
if __name__ == "__main__":
|
|||
|
|
script_dir = Path(__file__).parent
|
|||
|
|
sql_file = script_dir / "init_database.sql"
|
|||
|
|
|
|||
|
|
print("=" * 60)
|
|||
|
|
print("NEX Docus 数据库初始化")
|
|||
|
|
print("=" * 60)
|
|||
|
|
print(f"SQL 文件: {sql_file}")
|
|||
|
|
print(f"数据库地址: {DB_CONFIG['host']}:{DB_CONFIG['port']}")
|
|||
|
|
print("=" * 60)
|
|||
|
|
print()
|
|||
|
|
|
|||
|
|
execute_sql_file(sql_file)
|