相关疑难解决方法(0)

如何在多线程Python应用程序中共享单个SQLite连接

我正在尝试编写一个多线程Python应用程序,其中在线程之间共享单个SQlite连接.我无法让这个工作.真正的应用程序是一个令人讨厌的Web服务器,但以下简单的代码演示了我的问题.

下面成功运行示例代码需要做哪些更改或更改?

当我运行THREAD_COUNT设置为1的程序时,它工作正常,我的数据库按照我的预期更新(即,字母"X"被添加到SectorGroup列中的文本值).

当我在THREAD_COUNT设置为高于1的任何值的情况下运行它时,除1之外的所有线程都会过早地终止与SQLite相关的异常.不同的线程抛出不同的异常(没有可辨别的模式),包括:

OperationalError: cannot start a transaction within a transaction 
Run Code Online (Sandbox Code Playgroud)

(发生在UPDATE声明中)

OperationalError: cannot commit - no transaction is active 
Run Code Online (Sandbox Code Playgroud)

(发生在.commit()调用上)

InterfaceError: Error binding parameter 0 - probably unsupported type. 
Run Code Online (Sandbox Code Playgroud)

(发生在UPDATESELECT声明中)

IndexError: tuple index out of range
Run Code Online (Sandbox Code Playgroud)

(这个让我完全不解,它发生在语句中group = rows[0][0] or '',但只有在多个线程运行时)

这是代码:

CONNECTION = sqlite3.connect('./database/mydb', detect_types=sqlite3.PARSE_DECLTYPES, check_same_thread = False)
CONNECTION.row_factory = sqlite3.Row

def commands(start_id):

    # loop over 100 records, read the SectorGroup column, and write it back with "X" appended. …
Run Code Online (Sandbox Code Playgroud)

python sqlite multithreading

10
推荐指数
2
解决办法
3万
查看次数

标签 统计

multithreading ×1

python ×1

sqlite ×1