此处仅为代码demo示例,隐去部分细节实现:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# function:threading test
# author:liu
# time:2017.8.12
import MySQLdb,threading
# 子线程
def func(arg):
print '--------- thread %s is running ----------' %threading.current_thread().name
#此处执行子线程操作
print '---------- thread %s ended ----------' %threading.current_thread().name
# connect mysql database
conn = MySQLdb.connect(host = 'localhost', user = 'xxx', passwd = 'xxx', db = 'xxx', charset = 'utf8')
cursor = conn.cursor()
sql = 'SELECT * FROM `table_name` WHERE 1'
try:
cursor.execute(sql)
data = cursor.fetchall() #tuple
# 创建子线程
for task in data:
arg = task[1]
t = threading.Thread(target = func, args = (arg,))
t.start()
except:
print "Error: unable to fecth data"
# close mysql connect
conn.close()