Sqlite 原子读取和更新计数器?
我正在尝试使用 Python 提供的 SQLite 实现一个简单的计数器。我正在使用 CGI 编写简单的动态网页。这是我能想到的实现计数器的唯一简单方法。问题是我需要先读取计数器值,然后更新它。但理想情况下,每个用户都应该读取唯一的值,并且如果两个用户同时读取,则可能会读取相同的计数器值。有没有一种简单的方法可以使读/写操作原子化?我不熟悉 SQL,所以请给出具体的说明。提前致谢。
我使用一列一行的表来存储计数器。
I am trying to implement a simple counter using SQLite provided with Python. I am using CGI to write simple dynamic web pages. It's the only simple way I can think of to implement a counter. The problem is I need to first read the counter value and then update it. But ideally, every user should read a unique value, and it's possible for two users to read the same counter value if they read simultaneously. Is there a simple way to make the read/write operation atomic? I unfamiliar with SQL so please give specific statements to do so. Thanks in advance.
I use a table with one column and one row to store the counter.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以尝试以下 SQL 语句流程:
当您以三等分方式执行更新时,只有在执行更新的连接上才能看到更改。在本例中,我们使用EXCLUSIVE事务,它会为其他客户端锁定数据库,直到它提交事务为止。
You may try this flow of SQL statements:
While you perform updates in trisection, changes can be seen only with connection on which they was performed. In this case we used EXCLUSIVE transactions, which locks database for other clients till it will commit transaction.
完整代码:
The complete code:
您最好不要在事务中使用 EXCLUSIVE 关键字,以提高效率。第一个 select 会自动创建一个共享锁,然后 update 语句会将其转换为独占锁。只需要 SELECT 和 UPDATE 都位于显式设置事务内即可。
You should better not use the EXCLUSIVE keyword in the transaction to make it more efficient. The first select automatically creates a shared lock and the update statement will then turn it into an exclusive. It is only necessary that the SELECT and the UPDATE are both inside an explicit set transaction.