我应该如何处理Python中访问sqlite数据库的多个线程?

Mic*_*ter 3 python sqlite multithreading

看来SQLite从3.7.13开始支持多线程访问,Python的sqlite3模块从3.4开始支持它。要使用它,您可以编写如下代码:

import sqlite3
dburi = "file:TESTING_MEMORY_DB?mode=memory&cache=shared"
connection = sqlite3.connect(dburi, uri=True, check_same_thread=False)
with connection:
    cursor = conneciton.cursor()
    cursor.execute("SQL")
Run Code Online (Sandbox Code Playgroud)

这是可行的,但您会发现的第一件事是您需要锁定对数据库的访问,否则另一个线程可能会损坏您的数据。这可能看起来像这样:

import threading
import sqlite3
dburi = "file:TESTING_MEMORY_DB?mode=memory&cache=shared"
connection = sqlite3.connect(dburi, uri=True, check_same_thread=False)
# NOTE: You'll need to share this same lock object with every other thread using the database
lock = threading.Lock()
with lock:
    with connection:
        cursor = connection.cursor()
        cursor.execute("SQL")
        connection.commit()
Run Code Online (Sandbox Code Playgroud)

现在,如果一个线程获取了锁,则另一个线程无法获取它,直到第一个线程关闭它,并且只要所有线程使用相同的lock对象并记住with lock:它们之前的with connection:对象,您的数据就不会被损坏。

但是,现在我需要一种方法来通过连接传递锁。您可以使用单独的参数或自定义类来执行此操作:

import threading
import sqlite3

class LockableSqliteConnection(object):
    def __init__(self, dburi):
        self.lock = threading.Lock()
        self.connection = sqlite3.connect(dburi, uri=True, check_same_thread=False)

dburi = "file:TESTING_MEMORY_DB?mode=memory&cache=shared"
lsc = LockableSqliteConnection(dburi)
with lsc.lock:
    with lsc.connection:
        cursor = lsc.connection.cursor()
        cursor.execute("SQL")
        lsc.connection.commit()
Run Code Online (Sandbox Code Playgroud)

这非常好,因为类的名称让我想起了我所拥有的内容,所以至少我不太可能忘记锁并损坏我的数据。但是有没有办法消除这两种with说法呢?理想情况下,我想将它们组合成一个with,因为无论如何我都不应该在没有锁的情况下使用连接。

Mic*_*ter 5

在本文的帮助下,我能够写出一些满足我需求的东西:http://effbot.org/zone/python-with-statement.htm

我的代码如下所示:

import threading
import sqlite3

class LockableSqliteConnection(object):
    def __init__(self, dburi):
        self.lock = threading.Lock()
        self.connection = sqlite3.connect(dburi, uri=True, check_same_thread=False)
        self.cursor = None
    def __enter__(self):
        self.lock.acquire()
        self.cursor = self.connection.cursor()
        return self
    def __exit__(self, type, value, traceback):
        self.lock.release()
        self.connection.commit()
        if self.cursor is not None:
            self.cursor.close()
            self.cursor = None
Run Code Online (Sandbox Code Playgroud)

此类的对象现在可以直接与以下with语句一起使用:

dburi = "file:TESTING_MEMORY_DB?mode=memory&cache=shared"
lsc = LockableSqliteConnection(dburi)
with lsc:
    lsc.cursor.execute("SQL")
Run Code Online (Sandbox Code Playgroud)

它还可以方便地为我打开一个游标,并自动提交我对数据库所做的更改,这意味着调用我的新类的代码更短。这很好,但自动提交数据库更改实际上可能并不是最好的主意...在更复杂的场景中,您可能想要启动事务,然后中途回滚,该功能可能会导致麻烦。然而,我的 SQL 需求非常简单,而且我从不回滚,所以我暂时将它留在我的项目中。

  • 尝试了代码,似乎效果很好。尚未完全测试,但确实发现了一个问题。self.lock.release() 应该是“__exit__”函数中的最后一行。否则,在建立新连接时可以释放锁,从而导致新连接的游标设置为 None。 (4认同)