乐之之

知而行乐,乐而行之,天道酬勤,学无止境。
如何运用进程池和线程池内容保存至数据库?

进程池不能保存至数据库,分别将代码位置进行调整即可。

1、进程池代码位置。

  在运用进程池保存数据至数据库时,进程池不能共享链接,所以在保存数据至数据库时,要把链接代码写到类的外面。

(1)链接数据库代码:

(2)提交保存代码:

sql = "insert into Vegetable_price (prodCat,prodName,lowPrice,avgPrice,highPrice,place,unitInfo) values (%s,%s,%s,%s,%s,%s,%s)"
params = [(prodCat,prodName,lowPrice,avgPrice,highPrice,place,unitInfo)]
cursor.executemany(sql,params)
db.commit()

(3)启动项代码内容:

if __name__ == '__main__':
    spider=Vegtable_Data()
    with ProcessPoolExecutor(10) as pe:
        for num in range(1,21):
            pe.submit(spider.parse_data,num)

2、线程池代码

在运用线程池保存数据至数据库时,线程池可以共享链接,而进程池不能,若要将链接数据库代码写进类里,只需把启动项里的进程池改为线程池即可。

(1)链接数据库代码:

(2)提交保存代码:

sql = "insert into Vegetable_price (prodCat,prodName,lowPrice,avgPrice,highPrice,place,unitInfo) values (%s,%s,%s,%s,%s,%s,%s)"
            params = [(prodCat,prodName,lowPrice,avgPrice,highPrice,place,unitInfo)]
            self.cursor.executemany(sql,params)
            self.db.commit()

(3)启动项代码内容:

if __name__ == '__main__':
    spider=Vegtable_Data()
    with ThreadPoolExecutor(10) as pe:
        for num in range(1,21):
            pe.submit(spider.parse_data,num)

 

posted on 2022-11-23 23:54  乐之之  阅读(136)  评论(0编辑  收藏  举报