You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

54 lines
1.7 KiB

"""MySQL数据库初始化脚本
创建数据库和表结构
"""
import sys
sys.path.insert(0, '.')
from sqlalchemy import create_engine, text
from app.core.config import get_config
from app.repositories.database import Base
def init_mysql():
"""初始化MySQL数据库"""
config = get_config()
db_config = config.database
# 连接MySQL服务器不指定数据库
server_url = f"mysql+pymysql://{db_config.user}:{db_config.password}@{db_config.host}:{db_config.port}"
print(f"Connecting to MySQL server: {db_config.host}:{db_config.port}")
engine = create_engine(server_url)
# 创建数据库
with engine.connect() as conn:
conn.execute(text(f"CREATE DATABASE IF NOT EXISTS {db_config.database} CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci"))
print(f"Database '{db_config.database}' created or exists")
# 连接到新创建的数据库
db_url = f"{server_url}/{db_config.database}"
db_engine = create_engine(db_url)
# 创建所有表
print("Creating tables...")
Base.metadata.create_all(bind=db_engine)
print("Tables created successfully!")
# 显示创建的表
with db_engine.connect() as conn:
result = conn.execute(text("SHOW TABLES"))
tables = [row[0] for row in result]
print(f"\nTables in database '{db_config.database}':")
for table in tables:
print(f" - {table}")
if __name__ == "__main__":
try:
init_mysql()
print("\nMySQL database initialization completed!")
except Exception as e:
print(f"Error: {e}")
import traceback
traceback.print_exc()
sys.exit(1)