首页 > 解决方案 > 为什么插入数据库时​​python比c ++快?

问题描述

我有一个包含 100 个元素的数组,称为“项目”

Python(大约需要 1 秒):

for item in items:
           cur.execute("INSERT INTO list VALUES (?)",(item,))
db.commit()

C++(9 秒):

for ( auto it = items.begin(); it != items.end(); ++it  ) {
    qry.prepare("INSERT INTO list VALUES (?)");
    std::string item = *it;
    qry.addBindValue(item);
    qry.exec();

C++ 没有prepare(9 秒):

for ( auto it = items.begin(); it != items.end(); ++it  ) {
    std::string item = *it;
    qry.exec("INSERT INTO list VALUES ('"+item+"')");

基本上我的问题是是否有一种方法可以insert像在 Python 中一样快速地在 C++ 中使用。

标签: pythonc++sqlite

解决方案


这是在 C++ 中快速批量插入的正确方法

花费不到 1 秒:

db.transaction();

for ( auto it = items.begin(); it != items.end(); ++it  ) {
    std::string item = *it;
    qry.exec("INSERT INTO list VALUES ('"+item+"')");
}

db.commit();

推荐阅读