【问题标题】:MySql insert speed too slowMySql插入速度太慢
【发布时间】:2020-11-18 20:47:52
【问题描述】:

我正在从事一个从 GitHub API 接收信息并对其进行分析的项目。问题是当我尝试插入这种巨大的数据时(例如在文件中我插入一个列表列表,如下所示,其中包含 19k 个项目)它需要很长时间。我该如何改进呢?谢谢。

       for i in commits_array:
            for j in i[-1]:
                self.insert_value_to_files_DB(j)


    def insert_value_to_files_DB(self, array):
    try:

        sql = "INSERT INTO files (file_count,file_sha,file_name,file_status,file_additions,file_deletions,file_changes,commit_sha) VALUES (%s, %s, %s, %s,%s, %s, %s,%s)"
        self.cursor.execute(sql, array)
        self.connection.commit()
    except mysql.connector.Error as error:
        print("Failed to insert into MySQL table {}".format(erro

【问题讨论】:

  • (1) 考虑使用executemany而不是execute,并且只使用一个commit (2) 将数据写入csv并使用MySQL的LOAD INFILE函数

标签: python mysql bulkinsert bulk-load


【解决方案1】:

19,000 行对于 dbms 来说并不算多。它很小。

在你开始插入行之前,做

self.connection.start_transaction()

然后每隔一百行左右做一次

self.connection.commit()
self.connection.start_transaction()

然后,当你完成后,做一个最终的 commit()。

在插入时,提交操作需要时间。将多行放入一个提交中会使事情变得更快。

【讨论】:

    猜你喜欢
    • 2012-08-04
    • 2020-02-22
    • 1970-01-01
    • 1970-01-01
    • 2015-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-28
    相关资源
    最近更新 更多