gevent多协程运用

#导包
import gevent
#猴子补丁
from gevent import monkey
monkey.patch_all()
from d8_db import ConnectMysql
import time
import pymysql


#协程入库
class MyInsertGevent(object):

    #定义协程方法
    def insert_gevent(self,startnum,endnum):
        #创建数据库连接
        my_connect = pymysql.connect(host='localhost',user='root',password='mysql',database='mymac',charset='utf8')
        #定义游标对象
        cursor = my_connect.cursor()
        #入库操作  参数开始结束
        for item in range(startnum,endnum):
            入库
            cursor.execute(' insert into `spider_data` values("%s","%s") ' %('123','456'))
            #事务提交数据库
            my_connect.commit()
        #关闭游标
        cursor.close()
        #关键数据库连接
        my_connect.close()


if __name__ == "__main__":
    a = time.time()
    #实例化协程入库
    myinsertgevent = MyInsertGevent()
    gevent.joinall([
        #创建协程
        gevent.spawn(myinsertgevent.insert_gevent,1,2000),
        gevent.spawn(myinsertgevent.insert_gevent,2001,4000),
        gevent.spawn(myinsertgevent.insert_gevent,4001,6000),
        gevent.spawn(myinsertgevent.insert_gevent,6001,8000),
        gevent.spawn(myinsertgevent.insert_gevent,8001,10000),

    ])
    #打印用时
    print(time.time()-a)

猜你喜欢

转载自www.cnblogs.com/Niuxingyu/p/10513435.html