test_mysql_config.py 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. """测试MySQL配置从.env文件读取"""
  2. from utils.mysql.mysql_pool import get_mysql_pool
  3. from utils.mysql.mysql_conn import get_mysql_conn
  4. def test_mysql_pool_from_env():
  5. """测试从.env文件读取MySQL连接池配置"""
  6. print("=== 测试从.env文件读取MySQL连接池配置 ===")
  7. # 使用默认配置创建连接池(应从.env文件读取)
  8. pool = get_mysql_pool()
  9. print(f"连接池配置 - 主机: {pool.host}")
  10. print(f"连接池配置 - 端口: {pool.port}")
  11. print(f"连接池配置 - 用户名: {pool.user}")
  12. print(f"连接池配置 - 数据库: {pool.database}")
  13. print(f"连接池配置 - 字符集: {pool.charset}")
  14. print(f"连接池配置 - 连接池大小: {pool.pool_size}")
  15. print("\n✓ 从.env文件读取MySQL连接池配置成功!")
  16. def test_mysql_conn_from_env():
  17. """测试从.env文件读取MySQL连接配置"""
  18. print("\n=== 测试从.env文件读取MySQL连接配置 ===")
  19. # 使用默认配置创建连接(应从.env文件读取)
  20. conn = get_mysql_conn()
  21. # 尝试执行简单查询
  22. try:
  23. # 获取游标上下文管理器
  24. with conn.get_cursor() as cursor:
  25. # 执行简单查询
  26. cursor.execute("SELECT 1 AS test")
  27. result = cursor.fetchone()
  28. print(f"执行简单查询结果: {result}")
  29. print("\n✓ 从.env文件读取MySQL连接配置成功!")
  30. except Exception as e:
  31. print(f"\n✗ 执行查询失败: {e}")
  32. finally:
  33. conn.close()
  34. def test_mysql_conn_with_custom_params():
  35. """测试自定义参数覆盖.env配置"""
  36. print("\n=== 测试自定义参数覆盖.env配置 ===")
  37. # 使用自定义参数创建连接
  38. conn = get_mysql_conn(database="test")
  39. try:
  40. # 获取游标上下文管理器
  41. with conn.get_cursor() as cursor:
  42. # 执行简单查询
  43. cursor.execute("SELECT 1 AS test")
  44. result = cursor.fetchone()
  45. print(f"执行简单查询结果: {result}")
  46. print("\n✓ 自定义参数覆盖.env配置成功!")
  47. except Exception as e:
  48. print(f"\n✗ 执行查询失败: {e}")
  49. finally:
  50. conn.close()
  51. if __name__ == "__main__":
  52. test_mysql_pool_from_env()
  53. test_mysql_conn_from_env()
  54. test_mysql_conn_with_custom_params()
  55. print("\n🎉 所有测试完成!")