Files
ai_game/server/init_db.py

41 lines
1.1 KiB
Python

import asyncio
import aiomysql
async def init_db():
# 连接 MySQL
conn = await aiomysql.connect(
host='localhost',
port=3306,
user='root',
password='liang20020523',
db='ai_game',
charset='utf8mb4'
)
try:
async with conn.cursor() as cursor:
# 读取 SQL 文件
with open('sql/schema_v2.sql', 'r', encoding='utf-8') as f:
sql_content = f.read()
# 分割 SQL 语句(按分号分隔)
statements = [s.strip() for s in sql_content.split(';') if s.strip()]
# 执行每个语句
for stmt in statements:
if stmt and not stmt.startswith('--'):
try:
await cursor.execute(stmt)
print(f"✓ 执行成功")
except Exception as e:
print(f"✗ 执行失败:{e}")
await conn.commit()
print("\n数据库初始化完成!")
finally:
await conn.close()
if __name__ == '__main__':
asyncio.run(init_db())