mysql 和 python 中的多线程

multithreading in mysql and python

我正在学习 python 和 mysql,因此我想使用多线程写入 mysql 数据库

当我尝试这样做并尝试创建多个线程时,它显示错误,例如未找到连接,但如果我尝试使用 1 个线程,它工作正常,但速度较低,即 40 行 p/s

请帮助我做到这一点,如果我做错了,请告诉我是否有好的方法,谢谢

import mysql.connector
from queue import Queue
from threading import Thread

mydb = mysql.connector.connect(
  host="localhost",
  user="root",
  password="",
  database="list"
)


def do_stuff(q):
      while True:
            mycursor = mydb.cursor()
            a=  q.get()
            sql = "INSERT INTO demo1 (id, name, price, tmp) VALUES (%s, %s, %s, %s)"
            val = (a[0], a[1],a[3],a[2])
            mycursor.execute(sql, val)

            mydb.commit()
            q.task_done()

q = Queue(maxsize=0)
num_threads = 1 #if I try more then 1 it throw error "IndexError: bytearray index out of range"

for i in range(num_threads):
        worker = Thread(target=do_stuff, args=(q,))
        worker.setDaemon(True)
        worker.start()
        
        
def strt():
    mycursor = mydb.cursor()
    sql = f"SELECT * FROM demo ORDER BY id"
    mycursor.execute(sql)
    myresult = mycursor.fetchall()
    for x in myresult:
        q.put(x)
            
strt()

您好,为了进行交易,您必须打开与每个线程的连接。这是如何工作的,当您打开一个连接时,这些连接将通过池获取。如果您打开一个连接,则该连接始终由一个进程使用,而不让另一个进程连接。

它不会造成任何瓶颈,因为当一个连接空闲时,将从池中选择该连接。

Source