c++ - 使用 SQLite3 API (C++) 的线程安全的last_insert_rowid

标签 c++ multithreading sqlite

我有一个程序,它使用线程处理数据库(根据用户请求)。但有一个问题:

尽管可能性不大,但是当例如将用户插入数据库(他的详细信息)并且我想使用 int 找出他的标识符列值( sqlite3_int64 sqlite3_last_insert_rowid(sqlite*); )时,就有可能出现问题。功能。

尽管 API 通常是线程安全的,正如我所研究的那样,如果另一个线程在我插入我的表之后之前向同一个表中插入一行,则可能会出现问题我打了sqlite3_last_insert_row_id()

来自SQLite Documentation :

If a separate thread performs a new INSERT on the same database connection while the sqlite3_last_insert_rowid() function is running and thus changes the last insert rowid, then the value returned by sqlite3_last_insert_rowid() is unpredictable and might not equal either the old or the new last insert rowid.

如何防止这种情况发生?

我可以互斥所有数据库访问,但这在当前阶段会很麻烦,这是唯一的方法吗?

我也可以执行事务sql 查询,但这会具有我想要的相同效果吗?

最佳答案

为了防止多个线程相互干扰,您应该使用事务,并且每个线程都有一个数据库连接。

如果您确实想在线程之间共享相同的连接,则需要互斥锁。

关于c++ - 使用 SQLite3 API (C++) 的线程安全的last_insert_rowid,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31541436/

相关文章:

android - 按升序排列 SMS 消息

Android 内容 uri id 作为字符串

python - 如何使用SQLAlchemy在SQLite上创建全文检索索引并进行查询?

c++ - 我可以将enable_if替换为decltype吗

c++ - 标准输出和标准输入关系

java - 线程离开后重新启动

c# - 从多个线程无锁写入文件

c++ - Boost::thread 如何获取指向调用我的函数的线程的指针?

android - Qt 蓝牙服务器不能与 QCoreApplication 一起工作

c++ - 使用 STL 算法缓存复杂的比较函数?