作业描述:使用进程去读取execl列表中的数据,然后用线程写入数据库

    1. from MySQL import MySQl
    2. from config import mysql_info
    3. import openpyxl
    4. import threading
    5. import multiprocessing
    6. import threadpool,os
    7. lock=threading.Lock()
    8. mysql_object=MySQl(mysql_info)
    9. class InsertData:
    10. data_path="./data"
    11. # 获取数据
    12. @staticmethod
    13. def get_data(file_name):
    14. book=openpyxl.load_workbook(file_name)
    15. sheet=book.active
    16. data_list=[]
    17. for row in sheet.rows:
    18. row_data=[col.value for col in row]
    19. data_list.append(row_data)
    20. return data_list
    21. # 执行sql语句
    22. def run(self,data):
    23. numbers, string =data
    24. sql="insert into lxp_thread(num,string) values('%s','%s')"%(numbers,string)
    25. with lock:
    26. mysql_object.execute(sql)
    27. # 线程池运行
    28. def to_db(self,data_list):
    29. pool=threadpool.ThreadPool(10)
    30. reqs=threadpool.makeRequests(self.run,data_list)
    31. for req in reqs:
    32. pool.putRequest(req)
    33. pool.wait()
    34. # 主函数
    35. def main(self):
    36. pool=multiprocessing.Pool(5)
    37. for file in os.listdir(self.data_path):
    38. abs_path=os.path.join(self.data_path,file)
    39. data_list=self.get_data(abs_path)
    40. pool.apply_async(self.to_db,args=(data_list,))
    41. pool.close()
    42. pool.join()
    43. print("done!")
    44. #
    45. if __name__ == '__main__':
    46. my=InsertData()
    47. my.main()