SQLite原子读取并更新计数器吗? [英] Sqlite atomically read and update a counter?

查看:86
本文介绍了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.

推荐答案

您可以尝试以下SQL语句流:

You may try this flow of SQL statements:

BEGIN EXCLUSIVE TRANSACTION;
// update counter here
// retrieve new value for user
COMMIT TRANSACTION;

在三部分中执行更新时,只有在执行更改的连接上才能看到更改.在这种情况下,我们使用了 EXCLUSIVE 事务,该事务为其他客户端锁定数据库,直到它将提交事务为止.

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.

这篇关于SQLite原子读取并更新计数器吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆