run_add_updated_at.py 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. #!/usr/bin/env python3
  2. """为 points_consumption_log 表添加 updated_at 字段"""
  3. import pymysql
  4. import sys
  5. # 数据库配置
  6. DB_CONFIG = {
  7. 'host': '192.168.1.206',
  8. 'port': 3306,
  9. 'user': 'root',
  10. 'password': 'test123456',
  11. 'database': 'shudao_test',
  12. 'charset': 'utf8mb4'
  13. }
  14. def add_updated_at_column():
  15. """添加 updated_at 字段"""
  16. conn = None
  17. try:
  18. print("连接数据库...")
  19. conn = pymysql.connect(**DB_CONFIG)
  20. cursor = conn.cursor()
  21. # 检查字段是否已存在
  22. cursor.execute("""
  23. SELECT COUNT(*)
  24. FROM information_schema.COLUMNS
  25. WHERE TABLE_SCHEMA = 'shudao_test'
  26. AND TABLE_NAME = 'points_consumption_log'
  27. AND COLUMN_NAME = 'updated_at'
  28. """)
  29. exists = cursor.fetchone()[0]
  30. if exists:
  31. print("✓ updated_at 字段已存在,无需添加")
  32. return True
  33. # 添加字段
  34. print("添加 updated_at 字段...")
  35. cursor.execute("""
  36. ALTER TABLE points_consumption_log
  37. ADD COLUMN updated_at INT DEFAULT 0 COMMENT 'Unix时间戳' AFTER created_at
  38. """)
  39. conn.commit()
  40. print("✓ updated_at 字段添加成功")
  41. # 验证
  42. cursor.execute("SHOW COLUMNS FROM points_consumption_log LIKE 'updated_at'")
  43. result = cursor.fetchone()
  44. if result:
  45. print(f"✓ 验证成功: {result}")
  46. return True
  47. else:
  48. print("❌ 验证失败:字段未找到")
  49. return False
  50. except Exception as e:
  51. print(f"❌ 错误: {e}")
  52. if conn:
  53. conn.rollback()
  54. return False
  55. finally:
  56. if conn:
  57. conn.close()
  58. if __name__ == "__main__":
  59. print("=" * 60)
  60. print("为 points_consumption_log 表添加 updated_at 字段")
  61. print("=" * 60)
  62. success = add_updated_at_column()
  63. sys.exit(0 if success else 1)