MySQL大批量Update优化

  • 参考文章

https://www.cnblogs.com/dasn/articles/6094887.html

需求:

  • 根据一系列规则把文件分为几类,方便查询。
  • 这里使数据库中表结构冗余几列字段来匹配相应的规则,就是需要一条条去扫数据库中的数据,扫完把数据更新回数据库。
  • 问题出在大规模数据的更新上,数据量很大会很耗时。
  • 这里二十多万条数据若是逐条更新需要7/8分钟左右,把需要更新的数据插入到临时表再以表为单位进行更新操作就只需要1/2秒,性能提升还是十分明显的。

代码:

def truncate_patch_insert(_sql_util, sql_insert, list_mesh_all, table_name):
    delete_table_sql = "truncate table %s" % table_name
    _sql_util.update_data(delete_table_sql)
    for i in range(0, len(list_mesh_all), 1000):
        try:
            num = 1000 + i
            if num > len(list_mesh_all):
                _sql_util.insert_many_data(sql_insert, list_mesh_all[i: len(list_mesh_all)])
            else:
                _sql_util.insert_many_data(sql_insert, list_mesh_all[i: i + 1000])
        except Exception as err:
            logger.error("insert %s error =%s", (table_name, err))
            _sql_util.rollback()
            _sql_util.db_close()


def make_label_pss(_sql_util, file_all, pss_name):
    list_all = []
    for file_single in file_all:
        file_name = file_single[1].lower()
        short_name = os.path.basename(file_name)
        sub_type = 0
        for k in constPss:
            if file_name.startswith(k):
                sub_type = constPss[k]
                for st in sub_type:
                    (k, v), = st.items()
                    if short_name.find(k) > 0:
                        sub_type = v
                        break
                    sub_type = v
                break
        # print(type(file_single[0]))
        list_all.append([file_single[0], sub_type])

    sql_insert = """INSERT INTO PssTemp ( id, SubType ) VALUES (%s, %s)"""
    truncate_patch_insert(sql_util, sql_insert, list_all, "PssTemp")
    sql_table_update = """UPDATE %s as t1, PssTemp SET t1.SubType=PssTemp.SubType WHERE t1.id=PssTemp.id""" % pss_name
    sql_util.update_data(sql_table_update)


def scan_table(sql_util, mesh_table_name="", pss_table_name=""):
    list_mesh_all = []

    sql_select_pss = """select id, FileName from %s""" % pss_table_name

    res_mesh_pss = sql_util.select_all_data(sql_select_pss)

    make_label_pss(sql_util, res_mesh_pss, pss_table_name)

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Loganer

感谢

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

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

打赏作者

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

抵扣说明:

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

余额充值