Do I need a transaction for multiple queries in one string?

Viewed 49

https://github.com/SRombauts/SQLiteCpp

SQLite::Database    db("example.db3");
while(...)
{
    db.exec("INSERT INTO xxx VALUES(...)");
}

It's sample code for SQLite to insert data. If there's no transaction, each db.exec is slow, almost takes 1 second.

So, you need a transaction :

db.exe("BEGIN");
while(...)
{
    db.exec("INSERT INTO xxx VALUES(...)");
}
db.exe("END");

But if I make all queries into one string:

db.exec("INSERT INTO xxx VALUES(...);\
INSERT INTO xxx VALUES(...);\
INSERT INTO xxx VALUES(...);\
...
");

Do I still need a transaction?

1 Answers

If you want to insert 'everything' or 'nothing', then, YES. You still need a transaction. SQLite::Database::exec() internally calls sqlite3_exec() and semicolon separated SQL statement will not be executed atomically without a transaction.

Related