如何在Python中锁定sqlite3数据库?

2024-04-20 01:36:26 发布

您现在位置:Python中文网/ 问答频道 /正文

有没有办法在Python中显式获取sqlite3数据库的锁?


Tags: 数据库sqlite3办法
3条回答

我们可以使用多进程命令来锁定数据库的读写进程。我使用以下命令,它工作正常。 从多处理导入锁 l、 锁定() l、 获取() 读/写数据库 l、 释放()

显式锁定数据库的方法是启动事务,如documentation中所述:

When a database is accessed by multiple connections, and one of the processes modifies the database, the SQLite database is locked until that transaction is committed.

启动事务的一种方法是使用connection as a context manager

import sqlite3
con = sqlite3.connect(...)
...
with con:
    # Database is locked here

还要注意,默认情况下会发生一些事务implictly

By default, the sqlite3 module opens transactions implicitly before a Data Modification Language (DML) statement (i.e. INSERT/UPDATE/DELETE/REPLACE), and commits transactions implicitly before a non-DML, non-query statement (i. e. anything other than SELECT or the aforementioned).

在sqlite常见问题解答中,"Can multiple applications or multiple instances of the same application access a single database file at the same time?"

Multiple processes can have the same database open at the same time. Multiple processes can be doing a SELECT at the same time. But only one process can be making changes to the database at any moment in time, however.

无论是否使用with connection构造,在任何给定时间,只有一个进程可以从中读取数据并写入数据库。

相关问题 更多 >