python如何使用多线程_如何使用Python多线程处理MySQL连接

我有一个连接到MySQL数据库的主Python脚本,从中提取一些记录。根据返回的结果,它启动的线程数(类实例)与捕获的记录数相同。每个线程都应该返回数据库并通过将一个状态标志设置为不同的状态(“进程已启动”)来更新另一个表。

为了达到这个目的,我试着:

1.)将数据库连接传递给所有线程

2.)从每个线程打开一个新的数据库连接

但他们都没有工作。

在这两种情况下,我都可以使用try/except运行更新,但MySQL表没有更新,也没有生成错误。我在这两种情况下都使用了commit。

我的问题是在这种情况下如何处理MySQL连接?

根据前几条评论进行更新:MAIN SCRIPT

-----------

#Connecting to DB

db = MySQLdb.connect(host = db_host,

db = db_db,

port = db_port,

user = db_user,

passwd = db_password,

charset='utf8')

# Initiating database cursor

cur = db.cursor()

# Fetching records for which I need to initiate a class instance

cur.execute('SELECT ...')

for row in cur.fetchall() :

# Initiating new instance, appending it to a list and

# starting all of them

CLASS WHICH IS INSTANTIATED

---------------------------

# Connecting to DB again. I also tried to pass connection

# which has been opened in the main script but it did not

# work either.

db = MySQLdb.connect(host = db_host,

db = db_db,

port = db_port,

user = db_user,

passwd = db_password,

charset='utf8')

# Initiating database cursor

cur_class = db.cursor()

cur.execute('UPDATE ...')

db.commit()

你可能感兴趣的:(python如何使用多线程)