简体   繁体   中英

why is python faster than c ++ when inserting into a database?

I have an array of 100 elements called "items"

Python (take about 1 sec):

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

C++ (9 sec):

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++ without prepare (9 sec):

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

Basically my question is whether there is a way to use insert in C++ as fast as in Python.

This is a correct way for fast batch inserts in C++

Take less than 1 sec:

db.transaction();

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

db.commit();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM