How do I lock an entire SQLite connection (locked read + locked write)?

我只是一个虾纸丫 提交于 2019-12-20 06:26:29

问题


I have an sqlite3 db that is being accessed concurrently. I have ClientA that reads the state of some table (Column1 has rows A, B, C) and needs to update the table with new letters of the alphabet. If ClientB reads the state of the table before ClientA updates the table (say with the new letter D), then it's possible that both clients could (and in my case do) write D to the table - such that Column1 becomes A, B, C, D, D. But I need to ensure Column1 only has unique letters!

How do I lock the db connection so that its read AND write operations get exclusive access so that Column1 doesn't accidentally change states between some other read-write cycle?

It's hard to find anything about "locking a sqlite read" online because everyone seems more interested in unlocking the db. The following doesn't seem to give con's read operations exclusive access

con = sqlite3.connect(db, isolation_level='EXCLUSIVE', timeout=10)

Related:

  • File locking - read then write whilst locked
  • How perform SQLite query with a data reader without locking database?

回答1:


Just setting the isolation level is not enough. You must also place your exclusive statements in transaction:

con = sqlite3.connect(db, isolation_level='EXCLUSIVE', timeout=10)
con.execute('BEGIN EXCLUSIVE')
# Exclusive access here; no other transaction can access the database.
# 1. Check for presence of letter
# 2. Add the letter if it doesn't exist
con.commit()
con.close()


来源:https://stackoverflow.com/questions/40275855/how-do-i-lock-an-entire-sqlite-connection-locked-read-locked-write

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!