使用Python进行多线程MySQL插入

4 投票
1 回答
6506 浏览
提问于 2025-04-16 14:54

下面是我用来将数据上传到MySQL的多线程脚本。我觉得用线程来进行多个插入操作听起来不错。

但是,实际上并没有提高性能。MySQL设置为可以接受多个连接,但当我查看进程列表时,并没有看到我预期的5到10个连接。连接字符串是

有没有办法解决这个问题呢?

import  sys, threading, Queue pyodbc

class WorkerThread(threading.Thread):
 def __init__(self, queue):
    threading.Thread.__init__(self)
    self.queue = queue

 def run(self):
    while 1:
        try: # take a job from the queue
            id, null, null2, null3 = self.queue.get_nowait()

        except Queue.Empty:
            raise SystemExit


           In Here I have MySQl connecctions
                *** cxn = pyodbc.connect('DSN=MySQL;PWD=MLML;Option=3') 
            csr = cxn.cursor()
       typical insert , selects Updates


if __name__ == '__main__':
  connections =  25 

  # build a queue with tuples
  queue = Queue.Queue()

        queue.put(row[:3])

   # print queue   

 threads = []
 for dummy in range(connections):
    t = WorkerThread(queue)
    t.start()
    threads.append(t)

# wait for all threads to finish
 for thread in threads:
    thread.join()

连接字符串在最上面设置。我尝试过在工作线程中使用连接字符串,但效果并没有太大改善。在工作线程中,MySQL的操作是单向的,只能插入数据。表格会被清空后再插入数据。通常每个工作线程只处理一个表格。这个过程很快,而且系统是本地的。但我没有看到我预期的多个连接。

队列中有30到400个项目。

1 个回答

3

你的队列里有多少个项目?

所有操作都是在同一个表上吗?如果是这样的话,使用多线程可能没什么帮助,因为在进行选择、插入、更新或删除时,表会被锁住。

从你的例子中,我们看不到你是在哪里创建连接的。是每个线程都创建一个连接,还是所有线程共用一个连接?

如果有25个线程,它们可能也在争抢队列上的锁。

撰写回答