run_migration.py 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. #!/usr/bin/env python3
  2. """
  3. 数据库迁移脚本:为user表添加points字段
  4. """
  5. import pymysql
  6. import sys
  7. # 数据库配置
  8. DB_CONFIG = {
  9. 'host': '172.16.29.101',
  10. 'port': 21000,
  11. 'user': 'root',
  12. 'password': '88888888',
  13. 'database': 'shudao',
  14. 'charset': 'utf8mb4'
  15. }
  16. # 迁移SQL语句列表
  17. MIGRATION_STATEMENTS = [
  18. # 1. 添加积分字段
  19. "ALTER TABLE `user` ADD COLUMN `points` INT DEFAULT 0 COMMENT '积分余额' AFTER `role`",
  20. # 2. 为现有用户初始化积分
  21. "UPDATE `user` SET `points` = 100 WHERE `points` IS NULL"
  22. ]
  23. def run_migration():
  24. """执行数据库迁移"""
  25. connection = None
  26. try:
  27. print("正在连接数据库...")
  28. connection = pymysql.connect(**DB_CONFIG)
  29. cursor = connection.cursor()
  30. print("开始执行迁移...")
  31. # 逐条执行SQL语句
  32. statements = MIGRATION_STATEMENTS
  33. for i, statement in enumerate(statements, 1):
  34. if statement:
  35. print(f"\n执行语句 {i}:")
  36. print(f" {statement[:100]}...")
  37. cursor.execute(statement)
  38. print(f" ✓ 成功")
  39. connection.commit()
  40. # 验证结果
  41. print("\n验证迁移结果...")
  42. cursor.execute("SELECT id, username, points FROM `user` LIMIT 5")
  43. results = cursor.fetchall()
  44. print("\n用户积分数据:")
  45. print("ID\t用户名\t\t积分")
  46. print("-" * 40)
  47. for row in results:
  48. print(f"{row[0]}\t{row[1]}\t\t{row[2]}")
  49. print("\n✓ 迁移成功完成!")
  50. return True
  51. except pymysql.err.OperationalError as e:
  52. error_code, error_msg = e.args
  53. if error_code == 1060: # Duplicate column name
  54. print(f"\n⚠ 字段已存在,无需重复添加: {error_msg}")
  55. return True
  56. else:
  57. print(f"\n✗ 数据库操作错误: {error_msg}")
  58. return False
  59. except Exception as e:
  60. print(f"\n✗ 迁移失败: {str(e)}")
  61. if connection:
  62. connection.rollback()
  63. return False
  64. finally:
  65. if connection:
  66. cursor.close()
  67. connection.close()
  68. print("\n数据库连接已关闭")
  69. if __name__ == '__main__':
  70. success = run_migration()
  71. sys.exit(0 if success else 1)