且构网

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

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

更新时间:2022-05-27 22:08:51

显式锁定数据库的方法是启动事务,如 文档:

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).