import pymysql import os from dotenv import load_dotenv # 加载环境变量 load_dotenv() # 直接使用已知的数据库连接信息 host = 'localhost' user = 'root' password = 'taiyi1224' database = 'kamaxitong' print(f"Connecting to MySQL: host={host}, user={user}, database={database}") try: # 连接数据库 connection = pymysql.connect( host=host, user=user, password=password, database=database, charset='utf8mb4' ) try: with connection.cursor() as cursor: # 检查alembic_version表是否存在 cursor.execute("SHOW TABLES LIKE 'alembic_version'") result = cursor.fetchone() if result: # 表存在,更新版本号 # 使用较短的版本号以避免长度限制 cursor.execute("UPDATE alembic_version SET version_num = %s", ("20241119",)) print(f"Updated alembic_version to 20241119") else: # 表不存在,创建表并插入版本号 cursor.execute(""" CREATE TABLE alembic_version ( version_num VARCHAR(32) NOT NULL ) """) cursor.execute("INSERT INTO alembic_version (version_num) VALUES (%s)", ("20241119",)) print("Created alembic_version table and inserted version 20241119") connection.commit() # 验证更新 cursor.execute("SELECT * FROM alembic_version") result = cursor.fetchone() print(f"Current alembic version: {result}") except Exception as e: print(f"Error updating alembic_version: {e}") connection.rollback() finally: connection.close() except Exception as e: print(f"Error connecting to MySQL: {e}")