import pymysql import os # Database configuration DB_HOST = "49.233.26.60" DB_PORT = 3306 DB_USER = "root" DB_PASSWORD = "dianyue" SQL_FILE_PATH = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "doc", "数据库schema.sql") def init_db(): print(f"Connecting to {DB_HOST}...") try: connection = pymysql.connect( host=DB_HOST, port=DB_PORT, user=DB_USER, password=DB_PASSWORD, cursorclass=pymysql.cursors.DictCursor ) with connection: print("Connected successfully.") with connection.cursor() as cursor: # Read SQL file print(f"Reading SQL file from {SQL_FILE_PATH}...") with open(SQL_FILE_PATH, 'r', encoding='utf-8') as f: sql_content = f.read() # Split commands (this is a simple split, might need more robust parsing if procedures are involved) # The schema file uses simple statements ending in ; commands = sql_content.split(';') for command in commands: command = command.strip() if command: print(f"Executing: {command[:50]}...") try: cursor.execute(command) except Exception as e: print(f"Error executing command: {e}") connection.commit() print("Database initialization completed.") except Exception as e: print(f"Failed to connect or execute: {e}") if __name__ == "__main__": init_db()