Python 和 sqlite3.ProgrammingError : Recursive use of cursors not allowed

标签 python multithreading sqlite database-cursor

我写了一个这样的 python 程序,应该在多线程模式下运行:

def Func(host,cursor,db):

    cursor.execute('''SELECT If_index, Username, Version, Community, Ip_traff FROM HOST WHERE
    Hostname = ?''',(host,))

    #do something

#--- Main ---

db = sqlite3.connect(os.getcwd()+'\HOST', check_same_thread = False) #opendatabase       
cursor = db.cursor()                                                 #generate a cursor

for ii in range(len(host)):  #host is a list of ipaddress

    #for each host i want generate a thread
    thr = threading.Thread(target = Func, args=(host[ii],cursor,db) 
    thr.start()

我收到 sqlite3.ProgrammingError:不允许递归使用游标。在这种情况下,我如何管理 sqlite3 的递归游标? 多谢 保罗

最佳答案

嗯,问题是 sqlite3 模块不喜欢多线程情况,您可以在 sqlite3 模块的文档中看到这一点

...the Python module disallows sharing connections and cursors between threads[1]

我要做的是在 Func 函数中使用某种同步,例如 threading.Lock[2]。您的 Func 将如下所示:

# Define the lock globally
lock = threading.Lock()

def Func(host,cursor,db):
    try:
        lock.acquire(True)
        res = cursor.execute('''...''',(host,))
        # do something
    finally:
        lock.release()

前面的代码会同步cursor.execute的执行,只让一个线程拿锁,其他线程会一直等到它被释放,当有锁的线程完成后,它会释放锁供其他线程使用拿去吧。

这应该可以解决问题。

[1] https://docs.python.org/2/library/sqlite3.html#multithreading

[2] https://docs.python.org/2/library/threading.html?highlight=threading#rlock-objects

关于Python 和 sqlite3.ProgrammingError : Recursive use of cursors not allowed,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26629080/

相关文章:

python - Python 中的 int 对象可以在函数内部变得可迭代吗?

具有函数属性的 Python 装饰器

c# - 将项目添加到用于 Parallel.ForEach c# 的 ConcurrentBag

返回值的 C# 任务

sql - 加入来自同一个表的两个结果集?

python - 从 CSV 文件中,计算一行中的唯一值并使用 python 打印总数

python - 如何使用 OpenCV-Python 更改某个区域的色调

multithreading - Goroutine 池是否像其他语言中的线程池一样有意义?

SQLite个人书籍数据库设计评论

java - 我无法删除 sqlite 中的日期