mysql_content_replace.py 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. import pymysql
  2. # 数据库连接配置
  3. host = '47.98.212.223'
  4. user = '6636'
  5. password = 'Mt7DiMvk7W_2'
  6. database = 'db-tm'
  7. # 要替换的字符串timichat.com .cn .net都替换为panygo.com
  8. string_to_replace = 'timichat.net'
  9. replacement_string = 'panygo.com'
  10. # 创建数据库连接
  11. conn = pymysql.connect(host=host, user=user,
  12. password=password, database=database)
  13. try:
  14. # 创建游标对象
  15. cursor = conn.cursor()
  16. # 获取数据库中的所有表名
  17. cursor.execute("SHOW TABLES;")
  18. tables = cursor.fetchall()
  19. # 遍历每个表并进行数据替换操作
  20. for table in tables:
  21. table_name = table[0]
  22. # 获取表的列名列表
  23. cursor.execute(f"SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = %s AND TABLE_NAME = %s;",
  24. (database, table_name))
  25. columns = [column[0] for column in cursor.fetchall()]
  26. # 构造更新语句
  27. update_queries = []
  28. for column in columns:
  29. update_queries.append(
  30. f"UPDATE {table_name} SET `{column}` = REPLACE(`{column}`, %s, %s);")
  31. # 执行更新操作
  32. for query in update_queries:
  33. cursor.execute(query, (string_to_replace, replacement_string))
  34. # 提交事务
  35. conn.commit()
  36. print("数据替换完成。")
  37. except pymysql.Error as e:
  38. # 发生错误时回滚事务
  39. conn.rollback()
  40. print(f"数据替换出错:{e}")
  41. finally:
  42. # 关闭游标和数据库连接
  43. cursor.close()
  44. conn.close()