Python - 使用队列运行多个 mysql 插入,而无需等待完成



最基本的问题形式。我有一个从 csv 生成的多维列表。我有它,所以它的操作是这样的:

data = [['hello', 'world'],['hello','universe']]
for i in data:
    try:
        cursor.execute("""INSERT INTO MYTABLE (word1,word2) VALUES ('%s','%s')""" % (i[0],i[1]))
        cursor.execute("""INSERT random command here""" % ())
        conn.commit()
    except Exception:
        conn.rollback()

这行得通。但是,它必须先等待响应,然后才能尝试提交下一个响应。一次完成一个查询需要相当长的时间,所以我希望使用队列/线程来一次发送多个这些查询(10 个左右),同时它通过数百个这样的列表。

我已经阅读了几个关于队列和多线程的教程,但无法解决列表中的特定项目(甚至无法解决队列和多线程的工作原理)。我在下面尝试了(以及其他一些变体),但无法理解如何使用我的价值观:

def stuff(q):
    while True:
        try:
            cursor.execute("""INSERT INTO MYTABLE (word1,word2) VALUES ('%s','%s')""" % (q.get(x[0]),q.get(x[1])))
            cursor.execute("""Random command here""" % ())
            conn.commit()
        exception Exception:
            conn.rollback()
            cursor.execute(""""insert statement here""" % ())            
        q.task_done()
q = Queue(maxsize=0)
num_threads = 2
array = [['Hello','World'],['This','Is']]
for i in range(num_threads):
    worker = Thread(target=stuff, args=(q,))
    worker.setDaemon(True)
    worker.start()
for x in array:
    q.put(x)

我不确定如何处理"stuff"函数内数组中的其他项目,因此,我一直在猜测。我对队列/线程的掌握一般,但我发现谷歌搜索的所有教程都是单维数组。任何见解将不胜感激,因为我一直很难解决这个问题。谢谢。

编辑:更新示例以更具体。我有一个唯一的票号列表,它首先查询哪些不在数据库中。那些不在里面的,它放在一个多维列表中。然后我尝试将插入到实时表中,但如果其中一个键标识符不匹配,则会引发异常,然后我希望它们回滚并插入到不同的表中

我最终将所有变量打包到 q.put() 中,并将它们拆分到函数中。我猜还有更好的方法,但这是我能想到的最好的方法。我也像这样接受了Blender的建议。希望这会帮助其他人:

def stuff(q):
    while True:
        try:
            one, two = q.get().split(',')
            cursor.execute("""INSERT INTO MYTABLE (word1,word2) VALUES (%s,%s)""", (one,two)))
            cursor.execute("""Random command here""", ())
            conn.commit()
        exception Exception:
            conn.rollback()
            cursor.execute(""""insert statement here""", ())            
        q.task_done()
q = Queue(maxsize=0)
num_threads = 2
array = [['Hello','World'],['This','Is']]
for i in range(num_threads):
    worker = Thread(target=stuff, args=(q,))
    worker.setDaemon(True)
    worker.start()
for x in array:
    q.put(x[0]+','+x[1])

最新更新