我有一个程序,它使用线程处理数据库(根据用户请求)。但有一个问题:
尽管可能性不大,但是当例如将用户插入数据库(他的详细信息)并且我想使用 int
找出他的标识符列值( sqlite3_int64 sqlite3_last_insert_rowid(sqlite*);
)时,就有可能出现问题。功能。
尽管 API 通常是线程安全的,正如我所研究的那样,如果另一个线程在我插入我的表之后但之前向同一个表中插入一行,则可能会出现问题我打了sqlite3_last_insert_row_id()
。
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/