我有一个主要的 Python 脚本,它连接到 MySQL 数据库并从中提取一些记录。根据返回的结果,它会启动与抓取的记录一样多的线程(类实例)。每个线程都应该返回数据库并通过将一个状态标志设置为不同的状态(“进程已启动”)来更新另一个表。
为了实现这一目标,我尝试:
1.) 将数据库连接传递给所有线程
2.) 从每个线程打开一个新的数据库连接
但他们都没有工作。
在这两种情况下,我都可以使用 try/ except 运行更新,没有任何问题,但 MySQL 表尚未更新,也没有生成错误。我在这两种情况下都使用了提交。
我的问题是在这种情况下如何处理 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中使用多线程处理mysql的例子,我不知道
您的表和数据,因此,只需更改代码可能会有所帮助:
import threading
import time
import MySQLdb
Num_Of_threads = 5
class myThread(threading.Thread):
def __init__(self, conn, cur, data_to_deal):
threading.Thread.__init__(self)
self.threadID = threadID
self.conn = conn
self.cur = cur
self.data_to_deal
def run(self):
# add your sql
sql = 'insert into table id values ({0});'
for i in self.data_to_deal:
self.cur.execute(sql.format(i))
self.conn.commit()
threads = []
data_list = [1,2,3,4,5]
for i in range(Num_Of_threads):
conn = MySQLdb.connect(host='localhost',user='root',passwd='',db='')
cur = conn.cursor()
new_thread = myThread(conn, cur, data_list[i])
for th in threads:
th.start()
for t in threads:
t.join()
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)