update_price.py 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. # -*- coding: utf-8 -*-
  2. # Author : Charley
  3. # Python : 3.10.8
  4. # Date : 2025/12/10 16:14
  5. from mysql_pool import MySQLConnectionPool
  6. from loguru import logger
  7. def update_price_fields():
  8. """
  9. 更新 courtyard_detail_record 表中 sale_price 和 mint_price 字段的值
  10. 去除美元符号($)和逗号(,)
  11. """
  12. # 配置 MySQL 连接池
  13. sql_pool = MySQLConnectionPool(log=logger)
  14. if not sql_pool.check_pool_health():
  15. logger.error("数据库连接池异常")
  16. raise RuntimeError("数据库连接池异常")
  17. try:
  18. # 查询所有需要更新的记录
  19. query = "SELECT id, sale_price, mint_price FROM courtyard_detail_record WHERE sale_price IS NOT NULL OR mint_price IS NOT NULL"
  20. records = sql_pool.select_all(query)
  21. logger.info(f"共找到 {len(records)} 条记录需要更新")
  22. updated_count = 0
  23. for record in records:
  24. record_id = record[0]
  25. sale_price = record[1]
  26. mint_price = record[2]
  27. # 处理 sale_price
  28. if sale_price and isinstance(sale_price, str):
  29. cleaned_sale_price = sale_price.replace("$", "").replace(",", "")
  30. # 如果能转换为数字则更新,否则保持原值
  31. try:
  32. float(cleaned_sale_price)
  33. except ValueError:
  34. cleaned_sale_price = sale_price # 无法转换则保持原值
  35. # 处理 mint_price
  36. if mint_price and isinstance(mint_price, str):
  37. cleaned_mint_price = mint_price.replace("$", "").replace(",", "")
  38. # 如果能转换为数字则更新,否则保持原值
  39. try:
  40. float(cleaned_mint_price)
  41. except ValueError:
  42. cleaned_mint_price = mint_price # 无法转换则保持原值
  43. # 更新数据库记录
  44. update_query = "UPDATE courtyard_detail_record SET sale_price = %s, mint_price = %s WHERE id = %s"
  45. update_args = (cleaned_sale_price if 'cleaned_sale_price' in locals() else sale_price,
  46. cleaned_mint_price if 'cleaned_mint_price' in locals() else mint_price,
  47. record_id)
  48. try:
  49. sql_pool.update_one(update_query, update_args)
  50. updated_count += 1
  51. except Exception as e:
  52. logger.error(f"更新记录 ID {record_id} 失败: {e}")
  53. logger.info(f"成功更新 {updated_count} 条记录")
  54. except Exception as e:
  55. logger.error(f"更新价格字段时发生错误: {e}")
  56. raise e
  57. if __name__ == '__main__':
  58. update_price_fields()