如何在 Python 中锁定 sqlite3 数据库? [英] How to lock a sqlite3 database in Python?
问题描述
有没有办法在 Python 中显式获取对 sqlite3 数据库的锁?
Is there a way to explicitly acquire a lock on a sqlite3 database in Python?
推荐答案
显式锁定数据库的方法是启动事务,如 文档:
The way to explicitly lock the database is start a transaction as explained in the documentation:
当一个数据库被多个连接访问,并且其中一个进程修改了数据库时,SQLite 数据库将被锁定,直到该事务被提交.
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.
启动事务的一种方法是使用 作为上下文管理器的连接:
One way to initiate a transaction is use the connection as a context manager:
import sqlite3
con = sqlite3.connect(...)
...
with con:
# Database is locked here
另请注意,某些交易在默认情况下隐式发生:
Also note that some transactions happen implictly by default:
默认情况下,sqlite3 模块在数据修改语言 (DML) 语句(即 INSERT/UPDATE/DELETE/REPLACE)之前隐式打开事务,并在非 DML、非查询语句(即任何其他而不是 SELECT 或上述).
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).
这篇关于如何在 Python 中锁定 sqlite3 数据库?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!