#!/usr/bin/env python3 """ 测试远程数据库连接 """ import asyncio import urllib.parse async def test_remote_connection(): """测试远程数据库连接""" try: import aiomysql # 公网数据库信息 host = '120.79.247.16' # 或 aiedu.ireborn.com.cn port = 3306 user = 'root' password = 'Kaopeilian2025!@#' database = 'kaopeilian' print(f"正在连接到远程数据库 {host}:{port}/{database}...") # 直接连接测试 conn = await aiomysql.connect( host=host, port=port, user=user, password=password, db=database, charset='utf8mb4' ) cursor = await conn.cursor() await cursor.execute("SELECT VERSION()") version = await cursor.fetchone() print(f"✅ 成功连接到MySQL: {version[0]}") # 测试查询 await cursor.execute("SHOW TABLES") tables = await cursor.fetchall() print(f"✅ 数据库中有 {len(tables)} 个表") await cursor.close() conn.close() # 生成URL编码的连接字符串 password_encoded = urllib.parse.quote_plus(password) dsn = f"mysql+aiomysql://{user}:{password_encoded}@{host}:{port}/{database}?charset=utf8mb4" print(f"\n✅ 连接成功!") print(f"📝 SQLAlchemy连接字符串(已编码):") print(f" {dsn}") # 测试SQLAlchemy连接 from sqlalchemy.ext.asyncio import create_async_engine engine = create_async_engine(dsn, echo=False) async with engine.begin() as conn: result = await conn.execute(text("SELECT 1")) print(f"\n✅ SQLAlchemy连接测试成功!") await engine.dispose() except Exception as e: print(f"❌ 连接失败: {e}") import traceback traceback.print_exc() if __name__ == "__main__": from sqlalchemy import text asyncio.run(test_remote_connection())