python:多线程修改数据库数据(线程池)

文章介绍了一个使用Python脚本进行敏感数据清理的解决方案,特别是针对归档库中的历史数据。脚本利用多线程并行处理多个表,通过配置参数批量修改数据字段,达到快速清理的效果。同时,脚本还包括错误处理和日志记录功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

项目场景:

        归档库中存在大量历史数据,需要将其中敏感数据内容全不清空。


问题描述

        由于归档库表很多,且每个表中的数据字段还不一样,希望方便快速的将数据全不修改完。


解决方案:

        使用python脚本配置和多线程方式并行处理,参考代码:

import pymysql.cursors
import logging
import time
from concurrent.futures import ThreadPoolExecutor

log_format = "%(asctime)s - %(levelname)s - %(threadName)s - %(message)s"
logging.basicConfig(filename='log.log', level=logging.DEBUG, format=log_format)
# 每次批处理数量
batch_num = 1
# 每表处理总数
count = 2

def update_table_field(table, phoneField, timeField,max_id):
    # 连接数据库
    connect = pymysql.Connect(
        host='lizz.mysql.com',
        port=3306,
        user='lizz',
        passwd='test123',
        db='testpy',
        charset='utf8'
    )
    # 获取游标
    cursor = connect.cursor()
    sum = 0
    try:
        while sum < count:
            # 执行查询sql,.format替换{}
            selectSql = "SELECT id FROM {} where id>%s ORDER BY id LIMIT %s;".format(table)
            cursor.execute(selectSql, (max_id, batch_num,))
            results = cursor.fetchall()
            if not results:
                break
            # 取最大的id
            sum = sum + len(results)
            max_id = max(results)[0]
            # 提取所有 id
            ids = [str(row[0]) for row in results]
            # 执行update接口,%s字符串占位符
            updateSql = "UPDATE {} SET {} = null,{}={} WHERE id IN ({})" \
                .format(table, phoneField, timeField, timeField, ','.join('%s' for _ in ids))
            # 执行sql语句
            cursor.execute(updateSql, ids)
            # 提交到数据库执行
            cursor.connection.commit()
            logging.info(f"{table} {sum},maxid={max_id}")
            # 暂停 1秒,防止过快数据库扛不住
            time.sleep(1)
        logging.info(f"finish {table} {sum},maxid={max_id}")
    except Exception as e:
        logging.error(f"Exception {table},{sum},{max_id},{str(e)}")
    # 关闭数据库连接
    connect.close()


def baseUpdatedata():
    table_field_pairs = [
        ('table1', 'name', 'createtime',55),
        ('table2', 'age', 'updatetime',100)
    ]
    executor = ThreadPoolExecutor(max_workers=2)
    for table, phoneField, timeField ,max_id in table_field_pairs:
        executor.submit(update_table_field, table, phoneField, timeField,max_id)
    # 关闭线程池
    executor.shutdown()
    logging.info("all finish!")


# 主函数执行
if __name__ == '__main__':
    baseUpdatedata()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

lizz666

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值