使用Python在MySQL中插入大型文本文件

时间:2019-07-07 17:28:29

标签: mysql python-3.x

我有一个很大的文本文件,其中包含逗号分隔的数据。但是在文件内部,有多个数据块,由标签和分隔。 我需要将这些块插入mySQL的不同表中。

我正在逐行读取文件。 找到后,我会“创建不存在的情况”创建新表并开始逐行插入。

但这需要花费大量时间,因为该文件大约有100万行。

是否有更好的方法来加快插入过程?

下面是我正在使用的代码

export const list = ( state = initialState, action ) => {
  switch (action.type) {
    case FETCH_LIST:      
      return [... action.list];
    case IS_ACTIVE_LIST:
      return state.map(i => i.id !== action.id.id ? 
        { ...i , active: false } : { ...i, active: true});
    default:
      return state
  }
}

示例文本文件。

    with open(file_name_with_path) as csv_file:
    csv_reader = csv.reader(csv_file,delimiter=',')
    line_count = 0
    start_count = 0
    new_file = False
    file_end = False
    ignore_line = False
    record_list = []
    file_name = ''

    temp_data = []

    for row in csv_reader:
        ignore_line = False
        if row[0].find('<START>') ==0:
            file_name = row[1]
            line_count = 0
            new_file = True
            ignore_line = True
        if row[0].find('<END>') == 0:
            file_end = True
            record_list.append(file_name + '_' + str(line_count))
            line_count = 0
            ignore_line = True
            print('End of a file.')
        if new_file == True:
            print('Start of a new file.')
            new_file = False
        if line_count == 0 and ignore_line is False and new_file is False:
            line_count += 1
            create_table(file_name,row)
            temp_data.append(row)
        elif ignore_line == False:
            line_count += 1
            add_data(file_name, row)
            temp_data.append(row)
    print(f'Processed the file - {",".join(record_list)}' )

1 个答案:

答案 0 :(得分:0)

您没有向我们显示您正在运行的代码。

您建议乐观地认为 应用程序级别的吞吐量约为40行/秒(50k / 1200), 我们都同意这是“低”的。 您应该能够轻松实现 性能提高一到两个数量级。

不清楚您使用的是本地实例还是远程实例。 可能您正在每秒对本地磁盘执行40次提交。 或者,您可能每秒要管理40条WAN往返消息。

您要使用的是具有批量大小的.executemany() 每个COMMIT插入大约一万行。 对于您的百万行,这大约是一百个COMMIT。

网上有大量示例,例如 https://pynative.com/python-mysql-insert-data-into-database-table/

相关问题