test_db_connection.py 3.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. """
  4. 测试数据库连接
  5. 验证数据库配置是否正确,连接是否正常
  6. """
  7. import sys
  8. from src.models import get_engine, init_db, DecodeVideo
  9. from src.models.database import get_database_url
  10. from src.utils.logger import get_logger
  11. logger = get_logger(__name__)
  12. def test_connection():
  13. """测试数据库连接"""
  14. print("=" * 60)
  15. print("数据库连接测试")
  16. print("=" * 60)
  17. try:
  18. # 1. 显示连接信息(隐藏密码)
  19. database_url = get_database_url()
  20. # 隐藏密码显示
  21. safe_url = database_url.split('@')[0].split(':')[0] + ':***@' + '@'.join(database_url.split('@')[1:])
  22. print(f"\n✓ 数据库连接URL: {safe_url}")
  23. # 2. 测试连接
  24. print("\n正在测试数据库连接...")
  25. engine = get_engine()
  26. # 尝试连接
  27. with engine.connect() as conn:
  28. result = conn.execute("SELECT 1 as test")
  29. row = result.fetchone()
  30. if row and row[0] == 1:
  31. print("✓ 数据库连接成功!")
  32. else:
  33. print("✗ 数据库连接测试失败")
  34. return False
  35. # 3. 测试表是否存在
  36. print("\n检查 decode_videos 表...")
  37. from sqlalchemy import inspect
  38. inspector = inspect(engine)
  39. tables = inspector.get_table_names()
  40. if 'decode_videos' in tables:
  41. print("✓ decode_videos 表已存在")
  42. # 显示表结构
  43. columns = inspector.get_columns('decode_videos')
  44. print(f"\n表结构 ({len(columns)} 个字段):")
  45. for col in columns:
  46. nullable = "NULL" if col['nullable'] else "NOT NULL"
  47. print(f" - {col['name']}: {col['type']} ({nullable})")
  48. # 统计记录数
  49. from src.models import get_db
  50. db = next(get_db())
  51. try:
  52. count = db.query(DecodeVideo).count()
  53. print(f"\n✓ 当前记录数: {count}")
  54. except Exception as e:
  55. print(f"⚠ 查询记录数时出错: {e}")
  56. finally:
  57. db.close()
  58. else:
  59. print("⚠ decode_videos 表不存在")
  60. print("\n是否要创建表?(y/n): ", end="")
  61. choice = input().strip().lower()
  62. if choice == 'y':
  63. print("\n正在创建表...")
  64. init_db()
  65. print("✓ 表创建完成")
  66. else:
  67. print("跳过表创建")
  68. print("\n" + "=" * 60)
  69. print("✓ 所有测试通过!")
  70. print("=" * 60)
  71. return True
  72. except Exception as e:
  73. print(f"\n✗ 数据库连接失败: {e}")
  74. print("\n请检查以下配置:")
  75. print(" 1. 数据库主机地址是否正确")
  76. print(" 2. 数据库端口是否开放")
  77. print(" 3. 用户名和密码是否正确")
  78. print(" 4. 数据库名称是否正确")
  79. print(" 5. 网络连接是否正常(外网地址需要公网访问权限)")
  80. import traceback
  81. traceback.print_exc()
  82. return False
  83. if __name__ == "__main__":
  84. success = test_connection()
  85. sys.exit(0 if success else 1)