且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

SQLite 并发:第二个进程没有得到数据库更新

更新时间:2023-02-04 21:34:48

这适用于 sqlite3:从回答这个问题

This works fine with sqlite3: Moved from the answer to this question

import sqlite3, time
conn = sqlite3.connect('test.db')
conn.execute("CREATE TABLE IF NOT EXISTS kv (key text unique, value text)")

for i in range(1000):
    conn.execute('REPLACE INTO kv (key, value) VALUES (?,?)', (1, i))
    conn.commit()
    print i
    time.sleep(1)

script2.py

import sqlite3, time
conn = sqlite3.connect('test.db')
c = conn.cursor()

while True:
    c.execute('SELECT value FROM kv WHERE key = ?', (1,))
    item = c.fetchone()
    print item
    time.sleep(1)

输出

python script2.py 
(u'3',)
(u'4',)
(u'5',)
(u'6',)
(u'7',)

问题是您最初没有制作密钥 独特

The problem is that you originally haven't made your key unique

当违反 UNIQUE 或 PRIMARY KEY 约束时,REPLACE算法删除导致约束的预先存在的行在插入或更新当前行和命令继续正常执行.

When a UNIQUE or PRIMARY KEY constraint violation occurs, the REPLACE algorithm deletes pre-existing rows that are causing the constraint violation prior to inserting or updating the current row and the command continues executing normally.

如果 不是唯一的,就会发生以下情况:

Without the key being unique here's what happening:

sqlite3 test.db 
SQLite version 3.8.10.2 2015-05-20 18:17:19
Enter ".help" for usage hints.
sqlite> select * from kv;
1|0
1|1
1|2
1|3
1|4
sqlite> select * from kv;
1|0
1|1
1|2
1|3
1|4
1|5
sqlite> select * from kv;
1|0
1|1
1|2
1|3
1|4
1|5
1|6
1|7
sqlite> 

是的,sqlite3 支持事务,但有一些警告.因此,如果您还需要支持多个写入者 - 多个读取者 场景,由于锁争用,一切都可能变得有点棘手

And yes, sqlite3 supports transactions, with a few caveats though. So if you also need to support multiple writers - multiple readers scenario everything may become a bit tricky because of locks contention

这是一个相关 如果需要,可以讨论多位作家案例

Here's a related discussion on the multiple writers case if you need it