本文介绍了如何锁定整个 SQLite 连接(锁定读取 + 锁定写入)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个同时被访问的 sqlite3 数据库.我有 ClientA 读取某个表的状态(Column1 有行 ABC)并且需要用新的字母表更新表格.如果 ClientBClientA 更新表之前读取表的状态(比如使用新字母 D),那么两个客户端都可能(在我的情况下do)将 D 写入表格 - 使得 Column1 变成 AB、C、DD.但我需要确保 Column1 只有唯一的字母!

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!

如何锁定数据库连接,以便其读写操作获得独占访问权限,以便 Column1 不会在其他一些读写周期之间意外更改状态?

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?

在网上很难找到关于锁定sqlite读取"的任何信息,因为每个人似乎都对解锁数据库更感兴趣.以下似乎没有给出 con 的读取操作 独家访问

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)

相关:

推荐答案

仅仅设置隔离级别是不够的.您还必须在交易中放置您的独占声明:

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()

这篇关于如何锁定整个 SQLite 连接(锁定读取 + 锁定写入)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 09:51
查看更多