Connection.commit() 未将所有行上传到数据库

发布于 2025-01-14 20:25:17 字数 897 浏览 1 评论 0原文

我正在尝试使用 PyMySQL 从 CSV 文件填充 MySQL 数据库表。 CSV 文件大约有 948,000 行。该脚本工作正常,但数据库中只出现大约 840,000 行,我不知道其余的去了哪里。

我猜测这与 connection.commit() 方法有关,因此我尝试在脚本末尾以及每 10,000 个 INSERT 查询后提交,但到目前为止没有任何效果。有什么想法我可能做错了什么吗?

我在下面附上了相关的代码片段:

    with gzip.open(temp_file_path, "rt", encoding="utf-8") as f:
        reader = csv.reader(f)
        for row in reader:
            # if num % 10000 == 0:
                # conn.commit()
            print("[+] Processing row: ", num)

            sql = "INSERT INTO `{0}`({1}) VALUES({2})".format(table_name, ", ".join(columns),
                                                              ", ".join(["%s"] * len(columns)))
            result = cursor.execute(sql, row)
            if result == 1:
                num += 1
            else:
                print("Not inserted!")
    conn.commit()
    cursor.close()
    conn.close()

I am trying to populate a MySQL database table from a CSV file using PyMySQL. The CSV file has approx 948,000 rows. The script works fine but only approximately 840,000 rows appear in the database, I don't know where the rest go.

I am guessing this has something to do with connection.commit() method so I have tried committing at the end of the script as well as after every 10,000 INSERT queries but nothing works so far. Any ideas what I might be doing wrong?

I have attached the relevant code snippet below:

    with gzip.open(temp_file_path, "rt", encoding="utf-8") as f:
        reader = csv.reader(f)
        for row in reader:
            # if num % 10000 == 0:
                # conn.commit()
            print("[+] Processing row: ", num)

            sql = "INSERT INTO `{0}`({1}) VALUES({2})".format(table_name, ", ".join(columns),
                                                              ", ".join(["%s"] * len(columns)))
            result = cursor.execute(sql, row)
            if result == 1:
                num += 1
            else:
                print("Not inserted!")
    conn.commit()
    cursor.close()
    conn.close()

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文