如何在 C/C++ 中提交 SQLite 事务?

2022-01-06 00:00:00 sql c transactions sqlite c++

我正在使用 sqlite c/c++ 接口.

我有 3 个表(相关表),比如 A、B、C.现在,有一个名为 Set 的函数,它获取一些输入并根据输入将行插入这三个表中.(有时可能是其中一张表的更新)

现在我需要两件事.一,我不想要自动提交功能.基本上我想在每 1000 次调用 Set 函数后提交

其次,在 set 函数本身中,如果我发现在插入两个表后,第三次插入失败,那么我必须恢复 Set 函数调用中的那些特定更改.>

现在我没有看到任何暴露的 sqlite3_commit 函数.我只看到一个名为 sqlite3_commit_hook() 的函数,它在文档中略有不同.

是否有为此目的公开的任何功能?或者实现这种行为的方法是什么?

你能帮我找到最好的方法吗.

解决方案

您使用 sqlite3_exec 并分别传递BEGIN TRANSACTION"和END TRANSACTION".

//'db' 是你从 sqlite3_open* 得到的指针sqlite3_exec(db, "BEGIN TRANSACTION;", NULL, NULL, NULL);//此处执行的任何(修改)SQL 命令都不会提交,直到您调用:sqlite3_exec(db, "END TRANSACTION;", NULL, NULL, NULL);

这些 SQL 命令有同义词(例如 COMMIT 而不是 END TRANSACTION).作为参考,这里是 SQLite 交易文档.

I am using sqlite c/c++ interface.

I have 3 tables (related tables) say A, B, C. Now, there is a function called Set, which get some inputs and based on the inputs inserts rows into these three tables. (sometimes it can be an update in one of the tables)

Now I need two things. One, i dont want autocommit feature. Basically I would like to commit after every 1000 calls to Set function

Secondly, within the set function itself, if i find that after inserting into two tables, the third insert fails, then i have to revert, those particular changes in that Set function call.

Now i don't see any sqlite3_commit function exposed. I only see a function called sqlite3_commit_hook() which is slightly diff in documentation.

Are there any function exposed for this purpose? or What is the way to achieve this behaviour?

Can you help me with the best approach of doing this.

解决方案

You use sqlite3_exec and pass "BEGIN TRANSACTION" and "END TRANSACTION" respectively.

// 'db' is the pointer you got from sqlite3_open*
sqlite3_exec(db, "BEGIN TRANSACTION;", NULL, NULL, NULL);
// Any (modifying) SQL commands executed here are not committed until at the you call:
sqlite3_exec(db, "END TRANSACTION;", NULL, NULL, NULL);

There are synonyms for these SQL commands (like COMMIT instead of END TRANSACTION). For reference, here is the SQLite documentation for transactions.

相关文章