Python和sqlite3.ProgrammingError:不允许递归使用游标 [英] Python and sqlite3.ProgrammingError: Recursive use of cursors not allowed

查看:135
本文介绍了Python和sqlite3.ProgrammingError:不允许递归使用游标的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

i wrote a python program like this that should run in multithreading mode:

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的递归游标?多谢保罗

i receive the sqlite3.ProgrammingError: Recursive use of cursors not allowed. How can i manage the recursive cursor for sqlite3 in this case? thanks a lot Paolo

推荐答案

好吧,事实是sqlite3模块不喜欢多线程情况,您可以在sqlite3模块的文档中看到

Well, the thing is the sqlite3 module doesn't likes multithread cases, you can see that in the sqlite3 module's documentation

... Python模块不允许在线程之间共享连接和游标[1]

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

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

What I would do is to use some sort of synchronization in the Func function, for example, a threading.Lock[2]. Your Func will look like this:

# 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()

前面的代码将同步游标的执行.通过仅让一个线程获取锁来执行,其他线程将等待直到其被释放,当带有锁的线程完成时,它将释放锁以供其他线程使用拿走.

The previous code will synchronize the execution of the cursor.execute by letting just one thread take the lock, the other threads will wait until it's released, when the thread with the lock is done, it releases the lock for the others to take it.

那应该可以解决问题.

[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:不允许递归使用游标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆