python 多线程处理还是很方便
# coding=utf-8
from datetime import datetime
import pymysql.cursors
from faker import Factory
import random
import threading
#假数据制造工厂
faker = Factory.create('zh_CN')
def insert_data(threadName,num):
print 'run %s...'%(threadName)
mysql_conn = pymysql.connect(host= '127.0.0.1',
user= 'root',
password= '',
db= 'das',
charset='utf8mb4',
cursorclass=pymysql.cursors.DictCursor)
with mysql_conn.cursor() as cursor:
for _ in range(0,10):
create_time = faker.date_time_between_dates(datetime(2017,4,10),datetime(2017,5,10))
order_id = random.randint(1,30)
order_status = random.randint(1,5)
sql = "insert into `order` (`order_date_time`,`order_id`,`order_status`) values ('%s','%s','%s')" %(create_time,order_id,order_status)
print sql
cursor.execute(sql)
mysql_conn.commit()
mysql_conn.close()
#定义我的多线程处理
class myThread(threading.Thread):
def __init__(self,name,num):
threading.Thread.__init__(self)
self.name = name
self.num = num
def run(self):
insert_data(self.name,self.num)
#启动4个线程插入数据
threads = []
for i in range(1,5):
name = 'thread-%s' %(i)
new_th = myThread(name,50)
new_th.start()
threads.append(new_th)
for t in threads:
t.join()