关于多个单个insert语句转批量insert语句

本人廉价代码cv人 ,就是简单记录一下我对有些业务需求的通用记录。

为什么制造垃圾

    把多个insert合成一次多个的初中就是效率比较高,我所做的项目很多都是用flyway数据库版本控制的,有时候图方便就会把一些数据通过navicat导出出来,但是就会带来一个问题。
    有些数据库脚本就特别多,比如几十万行的一些记录,逐个insert执行起来就非常慢,甚至你启动一个服务半小时脚本都跑不完,我开发当然趁这个功夫喝个茶或者抽个烟就行,但是抵不住啊运维老哥来喷我,部署个服务nen半天呢。
    于是我就去搜索引擎嘛,没搜到,就自己拿python写了一个(图方便没拿java写)。

我制造的垃圾如下

def read_lines_and_combine(input_file, batch_size, old_substring, new_substring):
    combined_strings = []  # 存储合并后的字符串
    current_batch = []  # 存储当前批次的行数据

    with open(input_file, 'r') as f:
        for line in f:
            current_batch.append(line.strip())

            if len(current_batch) == batch_size:
                sql5000 = ("".join(current_batch)).replace(old_substring, new_substring)
                combined_strings.append(sql5000)
                current_batch = []

    # 处理剩余的不足batch_size行的数据
    if current_batch:
        sqlLast = ("".join(current_batch)).replace(old_substring, new_substring)
        combined_strings.append(sqlLast)
        combined_strings.append(sqlLast)

    return combined_strings


def write_to_output_file(output_file_path, strings_array):
    with open(output_file_path, 'w') as f:
        for string in strings_array:
            f.write(string + "\n")


# 示例
input_file = "input.sql"
output_file = "output.sql"
batch_size = 5000
combined_strings = read_lines_and_combine(input_file, batch_size, ";INSERT INTO `num_area` VALUES ", ",")

write_to_output_file(output_file, combined_strings)
# print("输出文件已生成:", output_file)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值